What's an effective way to refactor code that's yielding?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By jeff
:warning: Old Version Published before Godot 3 was released.

I mostly use yields with signals to pause a function until an animation is finished. A common use case, to my understanding.

One problem I regularly run into is when I want to refactor a chunk of code that’s yielding.

Say I have the following code:

doing_stuff1()
yield(get_node("AnimationPlayer"), "finished" )
doing_stuff2()
do_some_more_stuff()

and I end up wanting to refactor the first 3 lines into its own function call.

So I abstract it out and now the code is

doing_stuff_1_and_2()
do_some_more_stuff()

But the problem is that after refactoring, doing_stuff_1_and_2() returns immediately upon yielding, and so do_some_more_stuff() is called before the Animation is finished.

This is frustrating to me because (and admittedly I haven’t worked with coroutines before) I’m not used to refactoring changing the execution flow of my code.

How do people work around this? Maybe some sort of outside control structure?

How I’ve been doing it is just emitting another signal when doing_stuff_1_and_2() is complete and yielding to that in the main function, but I feel like this isn’t a good solution since more signals leads to harder to track execution flow.

Well, if you don’t yield in the main function, there is no reason for Godot to pause it.
And if you yield, what is going to resume it?
What you did looks ok to me, but I would not have done the refactoring, unless you have this repeated a lot in your code.

I’m learning this in C# currently, along with parallel task library. C# yield is iterator-based, not signal based. In my opinion, I find the GDScript yield a bit limited in comparison, hence the “bad feeling”. I tried to write some utilities, but it’s too late here, I have to sleep :expressionless:

Zylann | 2016-12-02 02:26

:bust_in_silhouette: Reply From: raymoo

I don’t think there is one, since function returns are mixed with coroutine yields.