Concurrency and Generators - jellyfish-tom/TIL GitHub Wiki

[SOURCES]

Javascript tried to manage concurrency/asynchronus code for quite some time now.

  1. Callbacks

They lead to Callback Hell - lets just forget about that shameful time. Callback hell was to be solved with:

  1. 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:

  1. 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.