Skip to content

Instantly share code, notes, and snippets.

@fengdi
Created June 5, 2014 18:31
Show Gist options
  • Select an option

  • Save fengdi/c0abcee8e4f5332e74ea to your computer and use it in GitHub Desktop.

Select an option

Save fengdi/c0abcee8e4f5332e74ea to your computer and use it in GitHub Desktop.

Revisions

  1. fengdi created this gist Jun 5, 2014.
    35 changes: 35 additions & 0 deletions Async
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    // An example of using yield to simplify the callback hell.
    // The limitation is, this only apply to whose callbacks take the normal form of function(err, result), more arguments are ignored.
    // Maybe there are many workarounds, but keep it simple, the ECMAScript 6 is around the corner.

    function Async(task) {

    var gen = task(callback);

    function callback(err, result) {

    if(err) {
    throw err;
    }
    else {
    gen.next(result);
    }

    };

    gen.next();

    };

    Async(function*(callback) {

    console.log(0);
    yield setTimeout(callback, 1000);
    console.log(1000);
    yield setTimeout(callback, 1000);
    console.log(2000);
    yield setTimeout(callback, 1000);
    console.log(3000);
    return;

    });