Introduction to ES6 Generators

Taking a nod from @Ogd and quote Isaac Schlueter (of the node.js project):
"Write small modules that each do one thing, and assemble them into other modules that do a bigger thing. You can't get into callback hell if you don't go there."

Exploring alternatives, I've been tinkering with and learning about generators. (Instead of building my team in Baltimore and being social.)

About ES6 Generators

Generators are functions, which can be stopped while in process and run later as many times as you want.

Example Code:

function *foo() {  
  var stop = yield 'woo';
  console.log(stop, 'inside foo');
}

var G = foo();

console.log( G.next() );  
// { value: 'woo', done: false }
console.log( G.next('bar') );  
// 'bar', 'inside foo'
// { value: undefined, done: true }

What was that? There are some new things to notice:

  1. * - just a sign that foo is a generator. You can put it anywhere between the function keyword and the function name, it does not matter exactly where.

  2. The yield expression - stops the generator and sends out the woo string. This pauses the state of the generator by sending the bar string into foo , which becomes the value returned by the yield expression inside foo (which gets assigned to stop). Context between all run -> stop -> run will be saved.

  3. The foo function has the next method that returns an object like { value: VALUE_FROM_YIELD, done: IS_THIS_FINISHED}.

Documentation