sribin sribin - 10 days ago 5
Javascript Question

JavaScript asynchronous programming: promises vs generators

Promises and generators allow you to write asynchronous code. I do not understand why both of these mechanisms are introduced in ECMA script 6. When is it best to use the promises, and when the generators?

Answer

There is no opposition between these two techniques. They coexist together complementing each other nicely. Promises give you capability to get result of an asynchronous operation which does not available yet. It solves Pyramid of Doom problem. So instead of:

function ourImportantFunction(callback) {
  //... some code 1
  task1(function(val1) {
    //... some code 2
    task2(val1, function(val2) {
      //... some code 3
      task3(val2, callback);
    });
  });
}

you can write:

function ourImportantFunction() {
  return Promise.resolve()
    .then(function() {
        //... some code 1
        return task1(val3)
    })
    .then(function(val2) {
        //... some code 2
        return task2(val2)
    })
    .then(function(val2) {
        //... some code 3
        return task3(val2);
    });
}

ourImportantFunction().then(callback);

But even with promises you must write code in asynchronous fashion - you must always pass callbacks to the functions. Writing asynchronous code is much harder then synchronous. Even with promises when the code is huge it becomes difficult to see the algorithm (well, it's very subjective, someone can argue with it. But for majority of programmers I think it's true). So we want to write asynchronous code in synchronous fashion. That's where generators are coming to help us. So instead of code above you can write:

var ourImportantFunction = spawn(function*() {
    //... some code 1
    var val1 = yield task1();
    //... some code 2
    var val2 = yield task2(val1);
    //... some code 3
    var val3 = yield task3(val2);

    return val3;
});

ourImportantFunction().then(callback);

where simplest possible spawn realization can be something like:

function spawn(generator) {
  return function() {    
    var iter = generator.apply(this, arguments);

    return Promise.resolve().then(function onValue(lastValue){
      var result = iter.next(lastValue); 

      var done  = result.done;
      var value = result.value;

      if (done) return value; // generator done, resolve promise
      return Promise.resolve(value).then(onValue, iter.throw.bind(iter)); // repeat
    });
  };
}

As you can see value (result of some asynchronous function task{N}) must be a promise. You can't do this with callbacks.

What remains to do is to implement spawn technique into language itself. So we are replacing spawn with async and yield with await and are coming to ES7 async/await:

var ourImportantFunction = async function() {
    //... some code 1
    var val1 = await task1();
    //... some code 2
    var val2 = await task2(val1);
    //... some code 3
    var val3 = await task3(val2);

    return val3;
}

I recommend you to watch this video to more understand this and some other coming techniques. If the guy speaks too fast for you, slow down the speed of playing ("settings" in right bottom corner, or just push [shift + <])

What is the best: just callbacks, or promises, or promises with generators - this is very subjective question. Callbacks is the fastest solution possible at this time (performance of native promises are very bad now). Promises with generators give you opportunity to write asynchronous code in synchronous fashion. But for now they much slower then simple callbacks.

Comments