Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

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) {
	   resolve('Success!');
	} else {
	  reject('Failure!');
	}
});

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

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

Promise.all()
Promise.prototype.catch()
Promise.prototype.then()
Promise.race()
Promise.reject()
Promise.resolve()

Promise.all()

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
   console.log(error);
});

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.

Leave a Reply