JavaScript Promise

The JavaScript Promise class and object is used for asynchronous task / calculation. A Promise represent an operation that hasn’t completed yet, but is expected in the future.

As word say itself “Promise”, Means it have to follow or do some task after completed it’s own work and task. In simple language that if you give the promise to another that I can reply you guaranteed, either with positive or negative reply based on the completion of my task.

In JavaScript it follow the same thing that, Promise complete it’s own task and after that it call the callback function based on the result of it’s own task.

Promise is used when we want to do task in asynchronous mode or long time task, but after that we also have to perform the some synchronous code or short time task, For e.g: Getting data from the server is asynchronous and long time task but displaying that data is synchronous or short term task.

Syntax of the Promise:

var promise = new Promise((success, fail)=>{
	if(true){
		success();
	}
	else{
		fail();
	}
});

If above syntax we created the object of the Promise class, In the constructors of the Promise we have to pass the two function which is success function and fail function which is called depends on the result of it’s own task.

Before the creating the object of the Promise or use the Promise, we have to check that user’s browser is supports the Promise or not. Let’s check it with simple if condition

if(window.Promise){
	// User's browser is supports the Promise
}
else{
	// User's browser is not supports the Promise
}

After creating the promise object you can pass the success and fail function in two ways, You can use any way which is easy to you:

//WAY 1:
promise.then(() => {
	alert("Success");
}).catch(() => {
	alert("Fail!!!");
});

//WAY 2:
promise.then(()=>{
	alert("Success!!!");
}, ()=>{
	alert("Fail!!!");
});

I recommended to you to use the WAY 1 because it is easy to understand and maintain the long code of block as well as creating the then chain and catch function simply.

Example of the Promise:

if(window.Promise){
	var promise = new Promise((success, fail)=>{
		if(true){
			success();
		}
		else{
			fail();
		}	
	});
	
	promise.then(() => {
		alert("Success");
	}).catch(() => {
		alert("Fail!!!");
	});
}

If you not check the user’s browser and it is not supported then it throw the error, If it is supports than it is good.

Promise can not automatically call the success or fail function, It was depends on us when we have to call the which function like if we want to call the success function than we can call it at any stage of point.

Promise is come with some methods that help us to catch the success and fail function callback, that is then and catch.

then

All promise instances get a then method which allows you to fire some code on the success of the promise or success callback of the promise.

then chaining

You can also create the chaining of then method, chaining of then method means if the promise is success than first then is called, if the first then is success then second then is called and it is continue process till all the then is executed.

If one of the then method from chaining then method get the fail callback then the remaining then method is not fired and catch method will fire due to fail callback.

For example if you have the 5 then in then chaining and your 3rd then get the fail callback then the reaming 4th and 5th then will note fired and it directly called the catch method.

catch

catch method helpful to catch the fail callback of the function, It helpful us to handle something if the the promise is fail.

Once the catch function is call then another remaining then function will not fired.

Example of then chaining:

var promise = new Promise((success, fail)=>{
	if(true){
		success();
	}
	else{
		fail();
	}
});

promise.then(() => {
	alert("SUCCESS: then 1");
}).then(() => {
	alert("SUCCESS: then 2");
}).then(() => {
	alert("SUCCESS: then 3");
}).catch(() => {
	alert("ERROR: catch handeled!!!");
});

//SUCCESS: then 1
//SUCCESS: then 2
//SUCCESS: then 3

We can also return the value from the promise, if we create the then chaining, so returning value of one then is become the input or parameter of the second then method. Let’s see the example of the returning value from the promise and then method.

var promise = new Promise((success, fail)=>{
	success(1);
});

promise.then((num) => {
  alert("SUCCESS 1: "+num); return num + 1;
}).then((num) => {
  alert("SUCCESS 2: "+num); return num + 1;
}).then((num) => {
  alert("SUCCESS 3:"+num); return num + 1;
}).catch(() => {
  alert("ERROR: catch handeled!!!");
});

//SUCCESS 1: 1
//SUCCESS 2: 2
//SUCCESS 3: 3

Promise.all

JavaScript Promise class have the static method called all, which is useful to us when we want to ensure that all the long and asynchronous task is successfully completed or not. For, e.g you want to perform some task only after the all AJAX request to server is successfully completed and get some data from the server, you can also say that in first AJAX request you want the table headers and in second AJAX request you want the table data, and after that you want to display the data on the screen, Then Promise.all is useful.

Promise.all example

var promise1 = new Promise((success, fail)=>{
	success(1);
});

var promise2 = new Promise((success, fail)=>{
	setTimeout(()=>{  success(2); }, 2000);
});

Promise.all([promise1, promise2]).then((results)=>{
  alert(results); // 1,2
  alert(results instanceof Array); // true
}).catch((results) => {
  alert(results);
});

In above example both promise call the success callback function so that’s why here then method will call and alert the result of both. Promise all’s then method have the array in it’s function parameter. It means Promise.all create the array of all the results and give us into the then method.

I know you have the one question that what if one of the promise is fail, means it call the fail method callback, So what Promise.all do, it simply call the catch method if one of the promise method is fail.

We can also say that Promise.all work like the && (and) operator if any one of the promise is fail then it call the catch method.

var promise1 = new Promise((success, fail)=>{
	success(1);
});

var promise2 = new Promise((success, fail)=>{
	setTimeout(()=>{  fail(2); }, 2000);
});

var promise3 = new Promise((success, fail)=>{
	setTimeout(()=>{  fail(3); alert(3); }, 3000);
});

Promise.all([promise1, promise2, promise3]).then((results)=>{
  alert(results);
}).catch((results) => {
  alert(results); // 2
  alert(results instanceof Array); // false
});

As I said above the Promise.all creates the array of all the result and return us into the then method. But in the case of the catch method it dose not return the array, Because the catch method is called the immediately after the one of the promise is getting fail, it does not wait to another promise to complete there task and it’s result, it directly call the catch method with the result of the fail promise and give us that result into the catch method.

It also can not terminated the remaining promise, It means all the remaining promise still are alive and complete there task but now it’s result are not considered.

Promise.race

race method will call the then or catch method early as much as possible, It means it will call the then or catch if one of the promise from the array of promise is completed.

If one promise is fail then it call the catch method, if success then call the then method. After calling the then or catch it does not considered the result of the remaining promise.

In simple language race means, race method only considered the result of the only one promise who complete it task before all another promises.

Promise.race example

var promise1 = new Promise((success, fail)=>{
	setTimeout(()=>{  success(1); }, 2500);
});

var promise2 = new Promise((success, fail)=>{
	setTimeout(()=>{  fail(2); }, 2000); 
	// This Promise complete it's taks before the all another Promise so
	// Promise.race will considered the results of this promise
	// This promise call the fail() method callback 
	// so Promise.race will call the catch method with the result of this method
});

var promise3 = new Promise((success, fail)=>{
	setTimeout(()=>{  fail(3); }, 3000);
});

Promise.race([promise1, promise2, promise3]).then((results)=>{
  alert(results);
}).catch((results) => {
  alert(results); // 2
});

JavaScript Promise Example:

var promise = new Promise((success, fail)=>{
	var objXHR = new XMLHttpRequest();

	objXHR.onreadystatechange=function(){
	  if(objXHR.readyState==4 && objXHR.status==200){
		success(JSON.stringfy(objXHR.responseText));
	  }
	  if(objXHR.readyState==4){
		fail("Sorry, Something goes wrong!!!");
	  }
	}

	objXHR.open("GET","http://www.javascripthive.info/helloAdmin.html");
	objXHR.send();
});

promise.then((msg)=>{
  alert(msg); // Custom message get from the server!!!
}).catch((msg) => {
  alert(msg); // Sorry, Something goes wrong!!!
});

In above example we create the one promise that made the request to server to get the welcome message for the user. after that we register the success and fail function to handle the response come from the server.

Promise class comes in picture with JavaScript ES6. So the old browser does not support the Promise like IE7, IE8, IE9 and more old browser so we can create the workaround for that.

Promise Workaround

Let’s create the promise workaround for the old browser, for that we mainly need the three function.

Promise Workaround Syntax:

function doTask(onsuccess, onfail){
  if(true){
	onsuccess("SUCCESS");
  }
  else{
	onfail("FAIL");
  }
}

function success(msg){
  alert(msg);
}

function fail(msg){
  alert(msg);
}

doTask(success, fail);

It is so much easy to create the workaround for it. Here I create the one function that have the two argument which is functions, one is success function and another is fail function, This function do some task and call the success function or fail function on the base of the result.

I create the another two function with named success and fail, It will called by the doTask function and at the end I called the doTask function with the two parameter which is function name.

Promise Workaround Example

function doTask(onsuccess, onfail){
	var objXHR = new XMLHttpRequest();

	objXHR.onreadystatechange=function(){
		if(objXHR.readyState==4 && objXHR.status==200){
			onsuccess(JSON.stringfy(objXHR.responseText));
		}
		if(objXHR.readyState==4){
			onfail("Sorry, Something goes wrong!!!");
		}
	}

	objXHR.open("GET","http://www.javascripthive.info/helloAdmin.html");
	objXHR.send();
}

function success(msg){
	alert(msg);
}

function fail(msg){
	alert(msg);
}

doTask(success, fail);

Above I created the example of the Promise workaround, which is same as the promise example. both will work same but this workaround will work on the all old browser.

If you notice above that I created the too many function without the using of the function keyword, I created all the function using the arrow(=>) operator, If you want to learn about the Arrow(=>) function then click here.

I hope you enjoy this tutorial, If you have question related this please comment down below.

Happy Coding!!!

🙂