Promise Design Pattern

Promises provides a powerful async pattern in Javascript. Lots and losts of API's use promises.

This is how we construct a promise (Promise producing code):

let promise = new Promise(function(resolve, reject){
  // executor : do something here...
})

The function passed to a new Promise is called the executor. The executor is called automatically and immediately by new Promise. When the executor obtains the result, it should call one of these callbacks:

The promise object returned by the new Promise constructor has these internal propterties:

The properties state and result of the Promise object are internal. We can't directly access them, we can use the methods .then() / .catch() / .finally() for that. These are called consumer functions in the world of Promise.

then

The most important, fundamental one is .then.

The syntax is:

  promise.then(function(result){}, function(error){});

catch

.catch(function(error){}) takes just one callback to handle errors.

The syntax is:

  promise.catch(function(error){});

finally

.finally() runs when a promise is settles, it doesn't matter wether the promise was resolved or rejected.