JavaScript promises are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. This tutorial will explore how promises work and how to use them effectively.
Understanding JavaScript Promises
1. What is a Promise?
A promise is an object that may be in one of three states:
- Pending: Initial state, neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
Example:
const myPromise = new Promise((resolve, reject) => {
// Simulating an asynchronous operation
const success = true; // Change to false to see rejection
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed.");
}
});
2. Using Promises
You can use the then
method to handle a fulfilled promise and the catch
method to handle a rejected promise.
myPromise
.then(result => {
console.log(result); // Output: Operation was successful!
})
.catch(error => {
console.error(error);
});
3. Chaining Promises
Promises can be chained to execute multiple asynchronous operations in sequence.
const firstPromise = new Promise((resolve) => {
resolve(10);
});
firstPromise
.then(result => {
console.log(result); // Output: 10
return result * 2;
})
.then(result => {
console.log(result); // Output: 20
return result * 2;
})
.then(result => {
console.log(result); // Output: 40
});
4. Promise.all
The Promise.all
method allows you to execute multiple promises in parallel and wait for all of them to be fulfilled.
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, "foo"));
const promise3 = 42;
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values); // Output: [3, "foo", 42]
});
5. Promise.race
The Promise.race
method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.
const promiseA = new Promise((resolve) => setTimeout(resolve, 500, "A"));
const promiseB = new Promise((resolve) => setTimeout(resolve, 100, "B"));
Promise.race([promiseA, promiseB]).then((value) => {
console.log(value); // Output: "B"
});
Conclusion
Promises provide a powerful way to manage asynchronous operations in JavaScript. By understanding how to use them effectively, you can write cleaner and more maintainable code.