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.


RESETRUNFULL
<!DOCTYPE html><html><body><script>

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);

</script></body><html>

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


RESETRUNFULL
<!DOCTYPE html><html><body><script>

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);

</script></body><html>

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