Tuesday, May 2, 2017

Promises in JavaScript


Promises

Promises in JavaScript are like promises in real life
  • A promise can only succeed or fail once
  • It cannot succeed or fail twice, neither can it switch from success to failure or vice versa
  • If a promise has succeeded or failed, we later add a success/failure callback. The correct callback will be called, even though the event took place earlier

State for promises

  Promises has 3 states. 
  Pending:   Hasn't fulfilled or resolved
  Resolved:  The action related to the promise Succeeded
  Rejected:   The action related to the promise failed

Callback in Promise

The promise has callback function. This callback function takes 2 arguments
The first argument is resolve and the second argument is reject

/**
 * Example for promise in Java Script
 */
//Declare a new promise
let promiseToReturn=new Promise(function(reject,resolve){

//returned
let returned=true;

//resolve function
if(returned)
{
resolve('been returned');
}
else
{
 reject('not been returned.');

}

}); 

//Execute the promise
//Then method is called when the promise is resolved
promiseToReturn.then(function(fromResolve){
        //We can get the status from resolved
        console.log("The book has"fromResolve);
    }).catch(function(fromReject)
    {
       console.log("The book has " +fromReject);   
      } 
    );

Output

Nested Promise 

We can have nested promise dependency as shown below.

1) Output of one promise would be input to another promise.
/*
Note :
We can do nested promise 
1) Where output of one promise would be input to another promise
2) Wait for all the promise to be completed
3) Notify if one of the promise is completed in an array of promises

**/
//Promise to open the door
let openCarDoor= function()
{
    return new Promise(function(resolve,reject)
    {
        resolve('Opened the Door');

    })
}
//Promise to start the car
//Note this function would have an input parameter
let startCar= function(message)
{
    return new Promise(function(resolve,reject)
    {
        resolve('Car has been started.');

    })
}
//Drive the car
//Note this function would have an input parameter
let driveCar= function(message)
{
    return new Promise(function(resolve,reject)
    {
        resolve('Car has is been driven.');

    })
}
//nested promise call 
openCarDoor().then(function(result)
{
    console.log(result);
    return startCar(result);
}).then(function(result){
        console.log(result);
         return driveCar(result);
        }).then(function(result){
            console.log(result);
                console.log("Finished.");
        });


2) Wait for all the promise to be completed . We would have this scenario when we have a condition where all needs to be satisfied.

//Nested promise
Promise.all([openCarDoor(),startCar(),driveCar()])
.then(function(result)
{
   console.log("Completed All"); 
});

3) Notify if one of the promise is completed in an array of promises. This scenario usually would  make sure that one of the promise is satisfied

//Nested promise
Promise.race([openCarDoor(),startCar(),driveCar()])
.then(function(result)
{
   console.log("Completed All"); 
});

Output
C:\Development\NodeProjects\vanilanode>node nestedPromise
Completed All

No comments:

Post a Comment