Saturday, 22 December 2018

What are promises in JavaScript?

ECMAScript2015 define promises, these are used to control the flow of asynchronous or deferred operations. In simple terms, a promise represents the completion or failure of an asynchronous operation.

At any point of time, a promise can be in one of the following states.

State
Description
pending
initial state, not fulfilled or rejected.
fulfilled
successful operation
rejected
failed operation.
settled
the Promise is either fulfilled or rejected, but not pending.

How to create a promise?
You can create a promise using Promise constructor function.

Syntax
new Promise( /* executor */ function(resolve, reject) { ... } );

As you see the Promise constructor definition, it takes an executor function as an argument, this executor function itself takes other two functions resolve and reject as arguments.  The executor normally initiates some asynchronous work, and then, once that completes, either calls the resolve function to resolve the promise or else rejects it if an error occurred. If an error is thrown in the executor function, the promise is rejected.

Let’s see with an example.

HelloWorld.js
function print_day_of_week(dayNumber){
  /* Create and return this promise */
  return new Promise((resolve, reject) => {
    if(dayNumber > 7){
      reject('Not A Valid Day');
    }else{
      resolve("Valid Day");
    }
  });
}

/* Prints Valid Day */
print_day_of_week(5).then(successMessage => {
  console.log(successMessage);
}).catch(failureMessage => {
  console.log(failureMessage);
})

/*Prints Not A Valid Day */
print_day_of_week(15).then(successMessage => {
  console.log(successMessage);
}).catch(failureMessage => {
  console.log(failureMessage);
})


Output
Valid Day
Not A Valid Day

You can even attach both resolve and reject callbacks in one shot using then function like below.

/* Prints Valid Day */
print_day_of_week(5).then(resolveCallback, rejectCallback);

/*Prints Not A Valid Day */
print_day_of_week(15).then(resolveCallback, rejectCallback);

HelloWorld.js
function print_day_of_week(dayNumber){
  /* Create and return this promise */
  return new Promise((resolve, reject) => {
    if(dayNumber > 7){
      reject('Not A Valid Day');
    }else{
      resolve("Valid Day");
    }
  });
}

var resolveCallback = function(successMessage){
  console.log("*************************");
  console.log(successMessage);
  console.log("*************************");
}

var rejectCallback = function(failureMessage){
  console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXX");
  console.log(failureMessage);
  console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXX");
}

/* Prints Valid Day */
print_day_of_week(5).then(resolveCallback, rejectCallback);

/*Prints Not A Valid Day */
print_day_of_week(15).then(resolveCallback, rejectCallback);


Output
*************************
Valid Day
*************************
XXXXXXXXXXXXXXXXXXXXXXXXXXXX
Not A Valid Day
XXXXXXXXXXXXXXXXXXXXXXXXXXXX

Chaining callbacks
One advantage of promises is, they can be chained. Using this, we can chain multiple asynchronous operations.

HelloWorld.js
function foo(x){
  
  return new Promise((resolve, reject) =>{
    if(x % 2 == 0){
      console.log("Multiplying the number");
      resolve(x * x);
    }else{
      console.log("Dividing the number by 2")
      reject(x / 2);
    }
  });
  
}

function fooResolveCallback(x){
  return new Promise((resolve, reject) =>{
    if( x > 100){
      console.log("x is > 100");
      resolve(x);
    }else{
      console.log("x is <= 100");
      reject(x);
    }
  });
}

function fooRejectCallback(x){
  return new Promise((resolve, reject) =>{
    if( x <= 100){
      console.log("x is <= 100");
      resolve(x);
    }else{
      console.log("x is > 100");
      reject(x);
    }
  });
}

var resolveCallback = function(successMessage){
  console.log("*************************");
  console.log(successMessage);
  console.log("*************************");
}

var rejectCallback = function(failureMessage){
  console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXX");
  console.log(failureMessage);
  console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXX");
}


foo(10).then(fooResolveCallback, fooRejectCallback).then(resolveCallback, rejectCallback)


Output
Multiplying the number
x is <= 100
XXXXXXXXXXXXXXXXXXXXXXXXXXXX
100
XXXXXXXXXXXXXXXXXXXXXXXXXXXX




Previous                                                 Next                                                 Home

No comments:

Post a Comment