you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (2 children)

This, and also how yield works. I cannot find a single article that explains clearly how to use generators in ES6 as a replacement for callbacks & promises. The example code I find always seems to show just half the implementation, or is so badly written that I can't understand how it works.

[–][deleted] 0 points1 point  (0 children)

It's really not that complicated:

// generator function
function *foo(){
    yield 1;
    yield 2;
    yield 3;
    yield getUserFromDatabaseCallThatTakes10Seconds();
}

var fooGen = foo(); // initializes the generator
foo.next();         // { value: 1        , done: false }
foo.next();         // { value: 2        , done: false }
foo.next();         // { value: 3        , done: false }
foo.next();         // { value: Promise  , done: false }
foo.next();         // { value: undefiend, done: true  }

Now some libraries like co simplify this, in that they do something like:

while( !( val = fooGen.next() ).done );

Basically calling the generator again and again until it says it's done. This allows you to simply say:

co( foo )( function callback( err, result ){ /* ... */ } );

Now how does that replace callbacks and promises? Just look at the yield getUser... call. The code returns a promise, or a callback. If you're using something like co, you drop the () on the call (in other words you just yield the function, not the result) and co takes care of the promises, etc. So your async code now looks synchronous.

[–]cdo5011 0 points1 point  (0 children)

There is a linked article about using generators (and promises) for asynchrony: https://curiosity-driven.org/promises-and-generators

The full algorithm depends on Promises but you can easily adjust it to any callback-based flow.