DEV Community

Puja Kundu
Puja Kundu

Posted on

A brief intro to JS Promises

A JS Promise is an object that represents the completion or failure of an asynchronous operation and gives results.

Syntax

The syntax for writing a promise by using the ‘new’ keyword and promise constructor function.
const myPromise = new Promise();
A promise has three states. That is -

  • Pending

  • Resolved

  • Rejected

Pending: When the state is ‘Pending’, it means the operation has neither been resolved nor rejected. Pending is the initial state, and the initial result is undefined.
Resolved: When the state is ‘Resolved’, it means the operation has been completed successfully and will give a result.
Rejected: When the state is ‘Rejected’, it means the operation has not been completed successfully and will give an error.

Promise state

How to reject or fulfill a promise?

For instance, you have an API where there is information such as product id, name, price, etc is stored. You make an API call. When you are making the API call, initially the state is pending and the promise has neither been resolved nor rejected. Now you want to show the data which in this case are the product pieces of information on the UI, and if any error occurs you want to show an error message.

State
States

Top comments (0)