Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

Explain the different states of a Promise

Topics
JAVASCRIPT
Edit on GitHub

TL;DR

A Promise in JavaScript can be in one of three states: pending, fulfilled, or rejected. When a Promise is created, it starts in the pending state. If the operation completes successfully, the Promise transitions to the fulfilled state, and if it fails, it transitions to the rejected state. Here's a quick example:

let promise = new Promise((resolve, reject) => {
// some asynchronous operation
if (success) {
resolve('Success!');
} else {
reject('Error!');
}
});

Different states of a Promise

Pending

When a Promise is first created, it is in the pending state. This means that the asynchronous operation has not yet completed.

let promise = new Promise((resolve, reject) => {
// asynchronous operation
});

Fulfilled

A Promise transitions to the fulfilled state when the asynchronous operation completes successfully. The resolve function is called to indicate this.

let promise = new Promise((resolve, reject) => {
resolve('Success!');
});

Rejected

A Promise transitions to the rejected state when the asynchronous operation fails. The reject function is called to indicate this.

let promise = new Promise((resolve, reject) => {
reject('Error!');
});

Further reading

Edit on GitHub