Tuesday, July 21, 2015

JavaScript Promises

What are promises?

 

Promises quickly become standard way we handle asynchronous operations in JavaScript. Everybody who code even little bit in JavaScript is familiar with callbacks. Essence of using callback functions in JavaScript passing a function as an argument in another function and later execute that passed-in function or even return it to be executed later.
There are several problems with callback. For example when you need to be sure that two callbacks finishes before you do something, you must introduce new variables to track state of each callback. Callbacks also lead to another problem, which you should be already familiar with: callback hell.

Callback hell

 

I think this all started with node.js and callback hell get a bad rap from the node.js community. This is because when you have your node application with express and mongoose then callbacks are all over the place.
When you need to perform number of actions in specific sequence in JavaScript,  you must use nested functions. Something like this:
asyncCall(function(err, data1){
    if(err) return callback(err);       
    anotherAsyncCall(function(err2, data2){
        if(err2) return calllback(err2);
        oneMoreAsyncCall(function(err3, data3){
            if(err3) return callback(err3);
            // are we done yet?
        });
    });
});
You can use promises to make this code prettier:
asyncCall()
.then(function(data1){
    // do something...
    return anotherAsyncCall();
})
.then(function(data2){
    // do something...  
    return oneMoreAsyncCall();    
})
.then(function(data3){
   // the third and final async response
})
.fail(function(err) {
   // handle any error resulting from any of the above calls    
})
.done();
Lot nicer isn't it?
You can see that instead of requiring a callback we are returning a Promise object. You can chain promises, so subsequent then() calls on the Promise object also return promises.
We don't need to check for error in every callback, but only at the end of promise chain. This is also feature of promises.

Promises are not only solution to callback hell. Some times callback hell is direct consequence of poor code organization. In some cases promises only hide underlying structural problems of code. I mean it you need 5 indention you're screwed anyway, and should fix your program. You can find here some of the hints how to resolve callback hell

Implementation 

 

Promises have arrived natively in JavaScript, but for the end I want to provide half baked promise implementation with comments, so you have feeling how promises are (could be) impelmented:
function Promise(fn) {
  var state = 'pending';
  var value;
  var deferred;
  
  //When function we passed is done, this will be called.
  //If then is called before resolve, then value for then is deffered to function outside promise.
  //If then is called after resolve, then value is readed from internal state.
  function resolve(newValue) {
    value = newValue;
    state = 'resolved';
    
    if(deferred) {
      handle(deferred);
    }
  }

  function handle(onResolved) {
    if(state === 'pending') {
      deferred = onResolved;
      return;
    }

    onResolved(value);
  }
  
  //This will be invoced when client calls it.
  this.then = function(onResolved) {
    handle(onResolved);
  };

  //Executing function that was passed into promise.
  //We are waithing until this function is finished.
  fn(resolve);
}

function testPromise() {
    return new Promise(function(resolve) {
        var value = readFromDatabase();
        resolve(value);
    });
}

testPromise().then(function(databaseValue) {
    log(databaseValue);
});

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

    ReplyDelete