JavaScript question detail
What is a promise
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) {
// Perform async operation
});
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)) // Logs after 5 seconds: "I'm a Promise!"
.catch((error) => console.error(error)) // Handles any rejection
.finally(() => console.log("Done")); // Runs regardless of success or failure
In the above example:
- A
Promiseis created to handle an asynchronous operation withresolveandrejectcallbacks. - The
setTimeoutresolves 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,
