Javascript promise with example

Javascript Promise are used to handle asynchronous operations. They are easy to manage when dealing with multiple asynchronous operations. In this tutorial we will see uses of javascript promise with example. So let’s get started javascript promise with example

Benefits of Promises

  • Improves Code Readability
  • Better handling of asynchronous operations
  • Better flow of control definition in asynchronous logic
  • Better Error Handling

A Promise has four states:

  • fulfilled: Action related to the promise succeeded
  • rejected: Action related to the promise failed
  • pending: Promise is still pending i.e not fulfilled or rejected yet
  • settled: Promise has fulfilled or rejected

Let see the promise syntax

var promise = new Promise(function(resolve, reject){
     //do something
});

Promise constructor takes only one argument, a callback function. Callback function takes two arguments, resolve and reject. Perform operations inside the callback function and if everything went well then call resolve. If desired operations do not go well then call reject.

Example: Promise

var promise = new Promise(function(resolve, reject) { 
  const x = "w3path"; 
  const y = "w3path"
  if(x === y) {
    resolve(); 
  } else { 
    reject(); 
  } 
})
.then(function () { 
    console.log('Success! Its working'); 
})
.catch(function () { 
    console.log('Failed! It has some error'); 
}); 

Output:

 Success! Its working 

then() is invoked when a promise is either resolved or rejected.

then() method takes two functions as parameters.

First function is executed if promise is resolved and a result is received.

Second function is executed if promise is rejected and an error is received. (It is optional and there is a better way to handle error using .catch() method. We will discuss catch() method later

Syntax:

.then(function(result){
   //handle success
}, function(error){
   //handle error
})

Example: Promise Resolved

var promise = new Promise(function(resolve, reject) { 
    resolve('Success! Its working'); 
})
.then(function(successMessage) { 
   //success handler function is invoked 
    console.log(successMessage); 
}, function(errorMessage) { 
    console.log(errorMessage); 
}) 

Output:

Success! Its working

Examples: Promise Rejected

var promise = new Promise(function(resolve, reject) { 
    reject('Promise Rejected') 
})
.then(function(successMessage) { 
    console.log(successMessage); 
}, function(errorMessage) { 
   //error handler function is invoked 
    console.log(errorMessage); 
}) 

Output:

Promise Rejected

catch() is invoked when a promise is either rejected or some error has occurred in execution.

Parameters:

catch() method takes one function as parameter. Function to handle errors or promise rejections.

Syntax:

.catch(function(error){
   //handle error
})

Examples: Promise Rejected

var promise = new Promise(function(resolve, reject) { 
    reject('Promise Rejected') 
})
.then(function(successMessage) { 
    console.log(successMessage); 
}) 
.catch(function(errorMessage) { 
   //error handler function is invoked 
    console.log(errorMessage); 
}); 

Finally

Just like there’s a finally clause in a regular try {…} catch {…}, there’s finally in promises.

The call .finally(f) is similar to .then(f, f) in the sense that it always runs when the promise is settled: be it resolve or reject.

finally is a good handler for performing cleanup, e.g. stopping our loading indicators, as they are not needed any more, no matter what the outcome is.

Examples: Promise with finally

new Promise((resolve, reject) => {
  resolve('Success! Its working')
})
.then(function(){

})
.finally(function() {
  // runs when the promise is settled, doesn't matter successfully or not

})

It’s not exactly an alias of then(f,f) though. There are several important differences:

  • A finally handler has no arguments. In finally we don’t know whether the promise is successful or not. That’s all right, as our task is usually to perform “general” finalizing procedures.
  • A finally handler passes through results and errors to the next handler.
  • Last, but not least, .finally(f) is a more convenient syntax than .then(f, f): no need to duplicate the function f.

Preview

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *