4 ms·
Do js generators resume from a yield point? Reading this thread I see no mentions of the fact that generators usually(?) resume from whatever branching-looping
by wruza 4y ago
Do js generators resume from a yield point? Reading this thread I see no mentions of the fact that generators usually(?) resume from whatever branching-looping state they were at yield, which is hard to simulate in general. A simple for(i){yield} - yes, just store an index somewhere and simulate to “resume” at it in your stream-like closure. A complex stateful algorithm with lots of cached lexical context - well, manageable with a corresponding data structure, but more expensive in terms of mapping it to a state table.
The whole point of a generator is its stack frame and its “instruction pointer”. You can implement a state machine right in regular code via cheap primitives. Otherwise the difference is just syntactical, afaiu.
- Jtsummers 4y agoI mean, you could look at the examples in the article and see that, yes, they resume from a yield point. But here's a simple illustrative example: function* bar() { yield 3; console.log("Resumed after the 3") yield 4; console.log("Resumed after the 4") } function* foo() { yield 1; console.log("Resumed after the 1") yield 2; console.log("Resumed after the 2") yield* bar(); } for(let n of foo()) { console.log(n); } Output: 1 Resumed after the 1 2 Resumed after the 2 3 Resumed after the 3 4 Resumed after the 4