A Promise is an object in JavaScript that represents the eventual success or failure of an asynchronous operation.
Real-life example:
You order food online.
- Pending — your food is being prepared.
- Fulfilled — your food has arrived successfully.
- Rejected — your order has failed.
These are the three states of a JavaScript Promise.
Pending:
The operation is still in progress.Fulfilled:
The operation completed successfully.Rejected:
The operation failed.Promise syntax:
const myPromise = new Promise((resolve, reject) => {
// Perform a task
resolve("Success!");
// reject("Something went wrong!");
});
Here:
- new Promise() — creates a Promise.
- resolve() — indicates successful completion.
- reject() — indicates failure.
Usually, you call either resolve() or reject() when the operation finishes.
- Simple Promise example:
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Task completed successfully!");
} else {
reject("Task failed!");
}
});
myPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
Output:
Task completed successfully!
Change success = true to success = false.
Output:
Task failed!
Top comments (0)