A Promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation.
The Three States of a Promise
A Promise always exists in one of three mutually exclusive states:
Pending: The initial state. The asynchronous operation is still running, and the promise is neither fulfilled nor rejected.
Fulfilled: The operation completed successfully. The promise now holds a resulting value.
Rejected: The operation failed. The promise now holds a reason (usually an error) for the failure.
Once a promise is either fulfilled or rejected, it becomes settled and its state can never change again.
Basic Syntax
Here is how you create and consume a basic Promise:
1. Creating a Promise
You use the new Promise constructor, which takes a function (called the executor) with two arguments: resolve and reject.
const myPromise = new Promise((resolve, reject) => {
let success = true; // Simulating the outcome of an operation
if (success) {
resolve("The operation was successful!");
} else {
reject("Something went wrong.");
}
});
2. Consuming a Promise
To handle the results of a promise, you use the .then(), .catch(), and .finally() methods:
myPromise
.then((value) => {
// Runs if the promise is fulfilled
console.log(value);
})
.catch((error) => {
// Runs if the promise is rejected
console.error(error);
})
.finally(() => {
// Runs no matter what, after the promise has settled
console.log("Operation finished.");
});
Modern Alternative: Async/Await
In modern JavaScript, you will often see the async and await keywords. This is built directly on top of Promises and allows you to write asynchronous code that looks and behaves like synchronous code:
async function executeTask() {
try {
const data = await fetchData(); // Waits until the promise resolves
const processed = await processData(data);
console.log(processed);
} catch (error) {
console.error("Caught an error:", error);
}
}
Top comments (0)