In JavaScript, a promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide a cleaner, more intuitive way to handle asynchronous code compared to traditional callback functions, helping to avoid issues like "callback hell."
A promise in JavaScript can be in one of three states:
1. Pending: The initial state, where the operation has not yet completed.
2. Fulfilled: The operation completed successfully, and the promise has a resulting value.
3. Rejected: The operation failed, and the promise has a reason for the failure.
When a promise is fulfilled or rejected, it is said to be "settled," meaning it will not change state again.
You can create a new promise using the Promise constructor, which takes a function (known as the executor) with two arguments: resolve and reject.
1. Example of Creating a Promise:
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed.");
}
});
Explanation:
success is true, the promise is resolved with a message.
success is false, the promise is rejected with an error message.
.then() and .catch()
To handle the result of a promise, you use the .then() method for fulfilled promises and the .catch() method for rejected promises.
2. Handling a Fulfilled Promise:
myPromise.then((message) => {
console.log(message); // Output: Operation was successful!
});
Explanation:
.then() method takes a function that runs when the promise is fulfilled.
3. Handling a Rejected Promise:
myPromise.catch((error) => {
console.error(error); // Output: Operation failed.
});
Explanation:
.catch() method takes a function that runs when the promise is rejected.
Promises can be chained to handle multiple asynchronous operations in sequence. Each .then() method returns a new promise, allowing you to chain additional .then() or .catch() calls.
4. Example of Chaining Promises:
myPromise
.then((message) => {
console.log(message);
return "Next operation";
})
.then((nextMessage) => {
console.log(nextMessage); // Output: Next operation
})
.catch((error) => {
console.error(error);
});
Explanation:
.then() resolves with a message and passes it to the next .then() in the chain.
.catch() method handles the error.
Promise.all() for Concurrent Promises
The Promise.all() method allows you to run multiple promises concurrently and waits until all of them are settled. It returns a single promise that resolves with an array of results or rejects with the first encountered error.
5. Example of Promise.all():
const promise1 = Promise.resolve("First");
const promise2 = Promise.resolve("Second");
const promise3 = Promise.resolve("Third");
Promise.all([promise1, promise2, promise3])
.then((results) => {
console.log(results); // Output: ["First", "Second", "Third"]
})
.catch((error) => {
console.error(error);
});
Explanation:
[promise1, promise2, promise3] are resolved, and the results are returned in the same order.
fetch() to handle asynchronous HTTP requests.
Promise.all() or Promise.race() to manage concurrent tasks.
.catch() to avoid unhandled promise rejections.
Promise.all() or Promise.allSettled() to handle multiple asynchronous operations efficiently.
Promises in JavaScript provide a powerful way to handle asynchronous operations, making your code more readable and manageable. By mastering promises, you can write more robust and efficient JavaScript applications.
Jorge García
Fullstack developer