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. ...

Get Express.js Blueprints now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.