A Promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It acts as a placeholder for a value that may not be available yet but will be resolved in the future.
A Promise can be in one of three states:
pending: Initial state, neither fulfilled nor rejected.
fulfilled: The operation completed successfully.
rejected: The operation failed (e.g., due to a network error).
Promise Syntax
const promise = new Promise(function (resolve, reject) {
});
Example: Creating and Using a Promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("I'm a Promise!");
}, 5000);
});
promise
.then((value) => console.log(value))
.catch((error) => console.error(error))
.finally(() => console.log("Done"));
In the above example:
- A
Promise is created to handle an asynchronous operation with resolve and reject callbacks.
- The
setTimeout resolves the promise with a value after 5 seconds.
.then(), .catch(), and .finally() are used to handle success, errors, and cleanup respectively.
The action flow of a promise will be as below,
