Close

JavaScript - Async Processing with JavaScript Promise

[Last Updated: May 7, 2019]

JavaScript ES6 introduced Promise API to do asynchronous processing.

A Promise represents an object which can return a result or error of an asynchronous computation at some point in future. This is similar to what we can do with CompletableFuture in Java.

Promise Constructor

Promise(executorFunction)

Where executorFunction is passed with arguments resolve and reject which are functions references. The executor function is executed immediately during Promise construction time. The executor function implementation should initiate some asynchronous work. Once that work completes the implementation should either:

  • call the 'resolve' function and pass the result object
  • or call the 'reject' function and pass the error object

Following example shows how to create an instance of Promise and implement the executor function:

let promise = new Promise(function(resolve, reject) {
  if(someCondition){
     resolve("done");
  }else{
     reject("error")
  }
});

Promise.then() method

This method can be used to consume asynchronous result or error. Following is its syntax:

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

The first argument callback function is called if promise's executor implementation calls 'resolve'. The second callback function is called if promise's executor implementation calls 'reject'.

The method then() returns immediately.

Following example shows a complete flow of how it works:

console.log('-- creating promise --');
let promise = new Promise(function (resolve, reject) {
  console.log('promise executor function is called');
  setTimeout(function () { //just add some delay
    if (Math.random() > 0.2) {
      resolve("done");
    } else {
      reject("not done")
    }
  }, 3000);
});

console.log('-- calling then --');
promise.then(
  function (result) {
    console.log("success result: " + result);
  },
  function (error) {
    console.log("error: " + error)
  });
console.log('-- after then --');
-- creating promise --
promise executor function is called
-- calling then --
-- after then --
success result: done

Promise.catch() method

This method can be used to consume error only. Following is its syntax:

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

Example:

console.log('-- creating promise --');
let promise = new Promise(function (resolve, reject) {
  console.log('promise executor function is called');
  setTimeout(function () {
    reject("not done")
  }, 3000);
});
console.log('-- calling catch --');
promise.catch(
  function (error) {
    console.log("error: " + error)
  });
console.log('-- after catch --');
-- creating promise --
promise executor function is called
-- calling catch --
-- after catch --
error: not done

Promise.finally()

This method can be used to receive callback on completion. Following is its syntax:

promise.finally(function(){}}

The callback function is called whether Promise is resolved successfully or rejected.

Examples:

console.log('-- creating promise --');
let promise = new Promise(function (resolve, reject) {
  console.log('promise executor function is called');
  setTimeout(function () {
    if (Math.random() > 0.1) {
      resolve("done");
    } else {
      reject("error")
    }
  }, 3000);
});
console.log('-- calling then --');
promise.then(
  function (result) {
    console.log("success result: " + result);
  },
  function (error) {
    console.log("error: " + error)
  })
  .finally(function () {
    console.log("-- post processing --")
  });
-- creating promise --
promise executor function is called
-- calling then --
success result: done
-- post processing --
console.log('-- creating promise --');
let promise = new Promise(function (resolve, reject) {
  console.log('promise executor function is called');
  setTimeout(function () {
    if (Math.random() > 0.1) {
      resolve("done");
    } else {
      reject("error")
    }

  }, 3000);
});
console.log('-- calling then --');
promise.finally(function () {
  console.log("-- pre processing --");
})
  .then(
    function (result) {
      console.log("success result: " + result);
    },
    function (error) {
      console.log("error: " + error)
    });
-- creating promise --
promise executor function is called
-- calling then --
-- pre processing --
success result: done

See Also