Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
Promise is an object that represents the result of an asynchronous operation. They allow working with deferred results without nested callbacks, making the code more readable. Earlier, I wrote a small post about what a Promise is. But now let's look at the structure and some methods.
What the Promise Structure Looks Like
Promise is created using the constructor new Promise(), which takes a function with two arguments: resolve and reject. This is the structure to remember. Let's look at an example:
const promise = new Promise((resolve, reject) => {
const success = Math.random() > 0.5;
setTimeout(() => {
if (success) {
resolve("Operation completed successfully");
} else {
reject("An error occurred");
}
}, 1000);
});
This code creates a promise that either resolves (resolve) with the string "Operation completed successfully" after one second (timeout 1000), or rejects (reject) with an error message. In other words, we created an emulation of a response success, waited a second, and received a result that depended on our random value in success.
Working with Promise
Promise has the methods .then(), .catch(), and .finally() for handling the result.
promise
.then(result => {
console.log("Success:", result);
})
.catch(error => {
console.log("Error:", error);
})
.finally(() => {
console.log("Operation completed");
});
Here, .then() gets the value from resolve, .catch() handles the error from reject, and .finally() executes always, regardless of the result. These methods are also worth remembering.
Promise Chains
The .then() method returns a new Promise, allowing for sequential (chained) execution.
new Promise(resolve => resolve(10))
.then(num => num * 2)
.then(num => num + 5)
.then(result => console.log("Result:", result));
Here, the initial value of 10 is multiplied by 2, 5 is added, and the result is 25.
Promise.all, Promise.race, and Promise.any
The Promise.all() method waits for the execution of all passed promises.
Promise.all([
new Promise(resolve => setTimeout(() => resolve("First"), 1000)),
new Promise(resolve => setTimeout(() => resolve("Second"), 2000))
]).then(results => console.log("All completed:", results));
And Promise.race() returns the first completed promise. This method is easy to remember by its name race - whoever finishes first wins.
Promise.race([
new Promise(resolve => setTimeout(() => resolve("First"), 1000)),
new Promise(resolve => setTimeout(() => resolve("Second"), 500))
]).then(result => console.log("First completed:", result));
Promise.any() is a method that takes an array of promises and returns the first successfully completed promise. If all promises are rejected, it returns an AggregateError.
const p1 = new Promise((_, reject) => setTimeout(() => reject("Error 1"), 1000));
const p2 = new Promise(resolve => setTimeout(() => resolve("Success 2"), 2000));
const p3 = new Promise(resolve => setTimeout(() => resolve("Success 3"), 3000));
Promise.any([p1, p2, p3])
.then(result => console.log("First successful result:", result))
.catch(error => console.log("All promises rejected:", error));
What happens in the example:
- p1 is rejected after 1 second.
- p2 is successfully completed after 2 seconds.
- Promise.any() returns p2, as it was the first successful one.
- If all promises are rejected, an AggregateError will be returned containing all errors.
This method is useful when you need to get the first successful result, ignoring the failures.
This post doesn't have any additions from the author yet.