Skip to content

Instantly share code, notes, and snippets.

@getify
Last active June 17, 2016 16:37

Revisions

  1. getify revised this gist May 28, 2016. No changes.
  2. getify created this gist May 28, 2016.
    38 changes: 38 additions & 0 deletions 1.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    // commented `run(..)`:

    function run(it) {
    // return a promise for the generator completing
    return Promise.resolve()
    .then( function handleNext(value){
    // run to the next yielded value
    var next = it.next( value );

    return (function handleResult(next){
    // generator has completed running?
    if (next.done) {
    return next.value;
    }
    // otherwise keep going
    else {
    return Promise.resolve( next.value )
    .then(
    // resume the async loop on
    // success, sending the resolved
    // value back into the generator
    handleNext,

    // if `value` is a rejected
    // promise, propagate error back
    // into the generator for its own
    // error handling
    function handleErr(err) {
    return Promise.resolve(
    it.throw( err )
    )
    .then( handleResult );
    }
    );
    }
    })(next);
    } );
    }
    26 changes: 26 additions & 0 deletions 2.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    // un-commented `run(..)`:

    function run(it) {
    return Promise.resolve()
    .then( function handleNext(value){
    var next = it.next( value );

    return (function handleResult(next){
    if (next.done) {
    return next.value;
    }
    else {
    return Promise.resolve( next.value )
    .then(
    handleNext,
    function handleErr(err) {
    return Promise.resolve(
    it.throw( err )
    )
    .then( handleResult );
    }
    );
    }
    })(next);
    } );
    }
    22 changes: 22 additions & 0 deletions 3.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    // ... with some ES6 sugar

    function run(it) {
    return Promise.resolve()
    .then( function handleNext(value){
    var next = it.next( value );

    return (function handleResult(next){
    return next.done ? next.value :
    Promise.resolve( next.value )
    .then(
    handleNext,
    err =>
    Promise.resolve(
    it.throw( err )
    )
    .then( handleResult )
    );
    }
    })( next );
    } );
    }