Generator Functions
Can be exited and later re-entered
- like closures, variables inside the generator function maintain state.
- when calling a generator function, an iterator object is returned. When we call
next()
on that object, all the code up until the firstyield
will be executed. Callingnext()
again will then execute all the code up until the secondyield
, and so on.- The function that calls the generator function is the iterator
- the generator function can pass values to the iterator object (
yield
). Anything that occurs afteryield
gets stored in the iterator'snext()
value- The generator function can also retrieve values from the iterator object (
next(___)
)
- The generator function can also retrieve values from the iterator object (
yield
returns execution to outside the generator function (ie. the context from which the gen fn was called), it's possible to usewhile(true)
, as long as there is a yield inside- This way,
next()
can keep getting called
- This way,
- spec:
next
is like async/await in the sense that it will execute code up until a point (yield
), then stop and wait for the availability of that data before continuing on - a generator function is a type of pull system. (ie. the Consumer determines when it receives data from the data Producer)
UE Resources
Backlinks