Promises in JavaScript

Promises are used to handle asynchronous operations in javascript. With promises, we can defer the execution of a code block until an async request is completed. It is also used to find out if the asynchronous operation is successfully completed or not.

Promises can produce a single value which is either a resolved value or a rejected value.

A Promise Object has one of three states :

  1. Pending: It is the initial state which is neither fulfilled nor rejected, the result is undefined
  2. Fulfilled: Indicates that the promised operation was successful, the result is a value
  3. Rejected:  Indicates that the promised operation failed, the result is an error object

Syntax :

const promise = new Promise((resolve, reject) => {
  // code execution  
  if (success) {
     resolve(value);
  } else {
     reject(error);
  }
});

promise.then((onFulfilled) => {
    console.log(onFulfilled);
})
.catch((onRejected) => {
    console.log(onRejected);
})
.finally(() => {
    render();
});

The Promise functions take and accept functions resolve() and reject() as an argument.

When the promise returns successfully, the resolve() function is called. and reject() function is called when an error occurs.

Promise Consumers

1then() method

To get the value of a promise when it’s fulfilled, you call the then() method of the promise object.

promise.then(onFulfilled,onRejected);

then() the method accepts two callback functions: onFulfilled and onRejected.

then() method calls the onFulfilled() with a value, if the promise is fulfilled or the onRejected() with an error if the promise is rejected.

Note: both onFulfilled and onRejected arguments are optional.

 

2. catch() method

If you want to get the error only when the state of the promise is rejected, you can use the catch() method of the Promise object:

promise.catch(onRejected);

3.finally() method

finally() method invoked when you want to execute the same piece of code whether the promise is fulfilled or rejected.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories