In Which State Can a Promise Be?

In Which State Can a Promise Be?

Ferenc Almasi β€’ Last updated 2020 November 05 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

Promise is always in one of the following three states:

  • pending: this is the initial state which we start from
  • fulfilled: this means the promise has been fulfilled successfully.
  • rejected: this means the promise has been rejected, there was an error.

To create a new Promise, call the Promise object with the new keyword:

Copied to clipboard!
new Promise((resolve, reject) => { ... });
promise.js

It accepts a callback function with two parameters:

  • A function for resolve
  • A function for reject

Call these funtions inside the callback of the promise to either resolve, or reject a promise.

Copied to clipboard! Playground
// βœ”οΈ Resolves promise with a value
new Promise((resolve, reject) => {
    resolve(value);
});

// ❌ Rejects promise with a reason
new Promise((resolve, reject) => {
    reject(reason);
});
promise.js

You can handle the return value of the promise, by calling the then handler, handle errors with a catch, or execute code after the promise is settled by either a fulfill or reject with finally.

Copied to clipboard! Playground
const promise = new Promise(...);

promise.then(result => console.log(result))
       .catch(error => console.log(error))
       .finally(info => console.log(info));
promise.js
What are the different states of promises?
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.