Monday, November 13, 2017

Promise in JavaScript, Understanding With Example

Hi, I am trying to explain here the Promise in JavaScript little bit with the help of example. Suppose we want to perform 3 tasks (task1, task2, task3), and we want to perform some other action when all three task are completed and we don't know how much time any task will take then surely we need to apply some logic in our code then we can achieve this but using Promises this is very easy to do.

Let's see this example:

Creating tasks using promises

 function task1(){
        return new Promise(function(resolve, reject){
         setTimeout(function(){
          resolve("Hello Task1 is done");  // we can use reject also on the basis of some condition.
         },5000)
        });
}
function task2(){
        return new Promise(function(resolve, reject){
         setTimeout(function(){
          resolve("Hello Task2 is done");
         },3000)
        });
}

function task3(){
        return new Promise(function(resolve, reject){
         setTimeout(function(){
          resolve("Hello Task3 is done");
         },7000)
        });
}

In above example I have taken setTimeout with some time but in real scenarios it can be some aync ajax request. Now suppose we need to perform some action on completing all three tasks.

Promise.all([task1(), task2(), task3()]).then(function(value){ 
    // do your action here
    console.log(value);
 });

// output for above code will come after 7 seconds as this is the maximum time that task3 will take:
["Hello Task1 is done", "Hello Task2 is done", "Hello Task3 is done"]

For more detail of Promise in JavaScript you can refer this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise