O'Reilly logo

Express.js Blueprints by Ben Augarten, Marc Kuo, Eric Lin, Aidha Shaikh, Fabiano Pereira Soriani, Geoffrey Tisserand, Chiqing Zhang, Kan Zhang

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Promises

A Promise is the eventual result of an asynchronous operation, just like giving someone a promise. Promises help handle errors, which results in writing cleaner code without callbacks. Instead of passing in an additional function that takes an error and result as parameters to every function, you can simply call your function with its parameter and get a Promise:

 getUserinfo('leo', function(err, user){
   if (err) {
    // handle error
     onFail(err);
     return;
   }
  
  onSuccess(user);
 });

versus

var promiseUserInfo = getUserinfo('leo');

promiseUserInfo.then(function(user) {
  onSuccess(user);
});

promiseUserInfo.catch(function(error) {
  // code to handle error
  onFail(user);
});

The benefit of using Promises isn't obvious if there is only one async operation. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required