Generators are functions that can be paused and resumed later. A generator can contain multiple yield
statements. At each yield
, the generator will pause/resume (while also returning some value). At every restart, a value will be passed in.
Here’s a brief intro to generator functions
With ES6 generators, we have a different kind of function, which may be paused in the middle, one or many times, and resumed later, allowing other code to run during these paused periods.
*
, e.g. function* foo() {}
1function* foo () {
2 // code goes here
3}
function* foo() {}
and function *foo() {}
are validyield
, and you send messages back in with every restart. Unlike regular function where you take in parameters at the beginning and give out messages once at the end with return
Web Workers are a mechanism where you can spin up a whole separate thread for a part of a JS program to run in, totally in parallel to your main JS program thread. The reason this doesn’t introduce multi-threaded complications into our programs is that the two threads can only communicate with each other through normal async events, which always abide by the event-loop one-at-a-time behavior required by run-to-completion.
.next()
on themreturn
inside a generator is highly discouraged bad practice. Always yield
inside a generator