DEV Community

Cover image for Power of Promises in JavaScript - Asynchronous Magic πŸ”₯
Bilal Asghar
Bilal Asghar

Posted on

Power of Promises in JavaScript - Asynchronous Magic πŸ”₯

Promise is a good way to handle asynchronous operations.

It's used to find out if the asynchronous operation is successfully completed or not.

A promise may have one of three states

  • Pending - process is not complete

  • Fulfilled - operation is successful

  • Rejected - an error occurs

Create a Promise

To create a promise object, we can use the Promise() constructor

let promise= new Promise(function(resolve,reject){
   //do something
})
Enter fullscreen mode Exit fullscreen mode

If the promise returns successfully, the resolve() function is called. And, if an error occurs, the reject() function is called.

Example

Let's suppose that the program below is an asynchronous program.

const count=true;
let countValue= new Promise(function(resolve,reject){
 if(count)
   {
     resolve("There is a count value");
   } else {
        reject("There is no count value");
   }
});
Enter fullscreen mode Exit fullscreen mode

Image description

Promise Chaining

Promises are useful when you have to handle more than one asynchronous task, one after another.
For that, we use promise chaining.
You can perform an operation after a promise is resolved using methods then(), catch() and finally().

Image description

then() Method

The then() method is used with the callback when the promise is successfully fulfilled or resolved.

promiseObject.then(onfulfilled,onRejected);
Enter fullscreen mode Exit fullscreen mode

You can chain multiple then() methods with the promise.

//returns a promise
let countValue = new Promise(function(resolve,reject)
 {
  resolve("Promise resolved");
 })

// execute when promise is resolved successfully.
countValue.then(function successValue(result){
     console.log("result");
}).then(function successValue1(){
     console.log("You can call  multiple functions this way.");
});

// Promise resolved
// You can call multiple functions this way
Enter fullscreen mode Exit fullscreen mode

catch() Method

The catch() method is used with the callback when the promise is rejected or if an error occurs.

//returns a promise
let countValue = new Promise(function(resolve,reject){
   reject("Promise rejected");
})

// execute when promise is resolved successfully.
countValue.then(function successValue(result){
    console.log("result");
}).catch(function errorValue(result){
    console.log("result");
});

// Promise rejected

Enter fullscreen mode Exit fullscreen mode

Promises Vs Callback

JavaScript Promise JavaScript Callback
The syntax is user-friendly and easy to read The syntax is difficult to understand
Error handling is easier to manage Error handling may be hard to manage

Top comments (0)