Concurrency and Generators - jellyfish-tom/TIL GitHub Wiki
[SOURCES]
- https://www.wptutor.io/web/js/generators-coroutines-async-javascript
- https://medium.freecodecamp.org/write-modern-asynchronous-javascript-using-promises-generators-and-coroutines-5fa9fe62cf74
- https://gist.github.com/ericelliott/890c20d18bcc4362048dba2dca8e67ac
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
Javascript tried to manage concurrency/asynchronus code for quite some time now.
- Callbacks
They lead to Callback Hell - lets just forget about that shameful time. Callback hell was to be solved with:
- Promises
But it haven't actually worked as we ended up in Promises Hell and it wasnt really working that much better than callbacks. And ES6/ES7 introduces:
- Async/Await
That works - asynchronous code looking and feeling like synchronous one. = WIN
and than come the:
Generators
Generators are a great metaprogramming tool. They can be used for things like lazy evaluation, iterating over memory intensive data sets and on-demand data processing from multiple data sources using a library like RxJs.
Syntax and basic usage:
function* generator(i) {
yield i;
yield i + 10;
}
var gen = generator(10);
console.log(gen.next());
// expected output: { value: 10, done: false }
console.log(gen.next());
// expected output: { value: 20, done: false }
console.log(gen.next());
// expected output: { value: undefined, done: true }
Values can also be passed inside generator function:
function* crossBridge() {
const reply = yield 'What is your favorite color?';
console.log(reply);
if (reply !== 'yellow') return 'Wrong!'
return 'You may pass.';
}
{
const iter = crossBridge();
const q = iter.next().value; // Iterator yields question
console.log(q);
const a = iter.next('blue').value; // Pass reply back into generator
console.log(a);
}
// What is your favorite color?
// blue
// Wrong!
However, often we wouldn’t want to use generators alone in production code because they forces us to reason about a process over time. And each time we call next, we jump back to our generator like a GOTO statement.