Advertisement
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
1const promise = new Promise(function (resolve, reject) {
2 // Perform async operation
3 });#### Example: Creating and Using a Promise
1const promise = new Promise((resolve, reject) => {
2
3setTimeout(() => {
4 resolve("I'm a Promise!");
5}, 5000);
6});
7
8promise
9 .then((value) => console.log(value)); // Logs after 5 seconds: "I'm a Promise!"
10 .catch((error) => console.error(error)) // Handles any rejection
11 .finally(() => console.log("Done")); // Runs regardless of success or failureIn 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,

Advertisement
JavaScript Coding Exercise 54
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement