JavaScript Promise

JavaScript Promise

Table of contents

No heading

No headings in the article.

Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code

A JavaScript promise is created with the help of the new keyword. Here’s the general syntax:

let some_action = new Promise(function(resolve, reject)

{
  // Perform some work
})

The Promise object takes a callback function as a parameter, which, in turn, takes two parameters to resolve and reject. The promise is either fulfilled or rejected.

There are three states

  1. Pending - The promise is pending when it's created. This means that the promise is yet to be fulfilled and the underlying operation is not yet performed.

  2. Fulfilled - This state indicates that the operation has finished and the promise is fulfilled with value.

  3. Rejected - This means that an error occurred during the process and the promise has been denied.

It’s known that if a promise is fulfilled, then some piece of code must be executed. And if it's rejected, then error handling must be performed. So for this, there are two methods

  1. then(callback) is invoked to attach a callback when the promise is resolved/fulfilled.

     .this(function(result){
     // handle success 
     }
    
  2. .catch(callback) method is invoked to attach a callback when the promise is rejected.

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

Once a promise is settled (either fulfilled or rejected), it's said to be immutable and cannot change its state.

promis.png

new Promise((resolve,reject) => {
    resolve("Promise Resolved!").than(setTimeout(console.log(value)),1000);
});

This promise is resolved after the given time it prints 'Arya Stark'; then the promise is fulfilled

new Promise((resolve,reject) => {
    reject("Rejected Promise!").catch(setTimeout(console.log(value)),1000);
})

and

new Promise((resolve,reject) => {
    reject("Rejected Promise!")
    .catch(console.log(value))
    .finally(console.log(`Promise Settled!`))
})

cover-6.png