If I yield to a Promise does it wait for the Promise to be resolved before continuing

- 1 answer

Ad

I am struggling to understand how to use generator functions and iterators to achieve various design options for a library I am thinking about writing.

Having got past the simple generator functions, I am now struggling with the examples out there on the internet showing how to integrate generators with Promises.

One problem is all the articles are written before the ES2015 spec on Promises was available and they all use 3 party libraries which I don't know what the nuances are.

So the question I don't really understand is if you yield and the generator function calls .next(Promise returning function) does the statements beyond the yield continue as soon as the .next function is called, or when the returned promise resolves. The examples seem to imply that it waits until the Promise resolves, but I don't see the logic of why.

Ad

Answer

Ad

generator function calls .next(Promise returning function)

No it doesn't. A generator needs to be driven by something, it doesn't run by itself.

does the statements beyond the yield continue as soon as the .next function is called

Yes. And this has nothing to do with the values you are yielding, be they promises or not.

To get the expected behaviour, that .next() is only called once the yielded promise fulfills (or that .throw is called when it rejects), you need to run the generator like that. In contrast to the proposed async/await syntax, generators don't do this theirselves. And that's where all those 3rd party libraries come in: you don't want to write this stuff yourself (neither do you want to repeat yourself everywhere, nor is it likely that you get it right on the first try).

Ad
source: stackoverflow.com
Ad