Promise

In the old days, while waiting for external input/output operations to finish, doing asynchronous operations continuously in a row would finally lead to the classic callback pyramid of doom.


f1(function(r1) {
  if (err) failureCallback();
  f2(r1, function(r2) {
    if (err) failureCallback();
    f3(r2, function(r3) {
      if (err) failureCallback();
      console.log('Got the final result: ' + r3);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

Now, we can form a promise chain instead, using: promise.then(successCallback[,errorCallback])....


p1.then(function(r1) {
  return f2(r1);
}).then(function(r2) {
  return f3(r2);
}).then(function(r3) {
  console.log('Got the final result: ' + r3);
}).catch(failureCallback);

Note that .then(), as well as .catch(), return another promise, thus enabling chaining.