Skip to content

JavaScript Promise API

Promises can replace the asynchronous use of callbacks, and they provide several benefits over them.

Basic Promise Usage

A new Promise is created with the new Promise() constructor and the promise provides resolve and reject functions to the provided callback. The fulfillment of the promise is simply logged, via a fulfill callback set using then() method.

let iWillComeHomeEarly = new Promise(function(resolve, reject) {
	// Do an async task ..
        let coming = true; // apply required logic...etc
	if(coming) {
	} else {

// execute the promise, once the execution is done, then method will be called.
iWillComeHomeEarly.then(function(messageFromSucessResolver) { 
	/* do something with the result */
}).catch(function(messageFromFailureRejct) {
	/* do something with the error */

A Promise is in one of these states

pending: initial state, not fulfilled or rejected.
fulfilled: it means the asynchronous operation has completed, and the promise has a value.
rejected: meaning that the operation failed, and the promise will never be fulfilled. In this state, a promise has a reason that indicates why the operation failed.

Promise methods



Sometimes we may have to execute multiple async interactions but only want to response when all of them are completed, yeah that’s where Promise.all() method comes in. The Promise.all() method takes an array of promises and fires one callback once they are all resolved.

var homeWorkPromise = function(){
  return new Promise(function(resolve,reject){
     var homeWorkCompleted = true;
    if(homeWorkCompleted) {
       return resolve('Home work completed');
    } else {
       return reject('Didn\'t finished my home work');

var officeWorkPromise = function(){
  return new Promise(function(resolve,reject){
     var officeWorkCompleted = true;
    if(officeWorkCompleted) {
       return resolve('Office work completed');
    } else {
       return reject('Didn\'t finished my office work');

Promise.all([homeWorkPromise(), officeWorkPromise()]).then(function(results) {
	// Both promises resolved
   console.log(results); // ["Home work completed", "Office work completed"]
}).catch(function(error) {
	// One or more promises was rejected

Lets change officeWorkCompleted = true to officeWorkCompleted = false than the promise will return rejected failed message.

Promise.all is rejected if one of the elements is rejected and Promise.all fails fast. If you have four promises which resolve after a timeout, and one rejects immediately, then Promise.all rejects immediately.

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments