Promise.allSettled is a new addition to the Promise API in ECMAScript 2020 that allows you to wait for multiple promises to resolve or reject, and then returns an array of objects that contains information about the status of each promise.
In this article, we will explore Promise.allSettled in depth with some code examples.
Why Promise.allSettled?
Before the introduction of Promise.allSettled, Promise.all was used to wait for multiple promises to resolve, and it would reject if any of the promises rejected. This meant that if one of the promises failed, the entire group of promises would fail, and you wouldn’t know which promise caused the issue.
Promise.allSettled fixes that problem by allowing you to wait for multiple promises to resolve or reject, without failing the whole group of promises. In addition, Promise.allSettled returns an array of objects that contains the status of each promise, regardless of whether it resolved or rejected.
Syntax
Promise.allSettled(iterable);
The parameter iterable is an iterable of Promise objects. It can be an Array, Map, Set, or any other iterable object.
Returns
A promise that resolves with an array of objects, where each object represents the status of a promise.
Properties of the Returned Objects
- status: A string that represents the status of the promise. Possible values are "fulfilled" or "rejected".
- value?: A value or undefined that represents the fulfillment value of the promise. This property is only present if status is "fulfilled".
- reason?: A value or undefined that represents the rejection reason of the promise. This property is only present if status is "rejected".
Examples
Let’s look at some code examples to understand how Promise.allSettled works.
Example 1: All Promises Resolved
In the following example, we create an array of two promises that resolve after a specific amount of time. We use Promise.allSettled to wait for all promises to resolve.
const promises = [
Promise.resolve("promise 1"),
Promise.resolve("promise 2"),
];
Promise.allSettled(promises)
.then((results) => {
console.log(results);
})
The output will be an array of two objects that represent the status of each promise:
[
{status: "fulfilled", value: "promise 1"},
{status: "fulfilled", value: "promise 2"},
]
Example 2: All Promises Rejected
In the following example, we create an array of two promises that reject after a specific amount of time. We use Promise.allSettled to wait for all promises to reject.
const promises = [
Promise.reject("promise 1"),
Promise.reject("promise 2"),
];
Promise.allSettled(promises)
.then((results) => {
console.log(results);
})
The output will be an array of two objects that represent the status of each promise:
[
{status: "rejected", reason: "promise 1"},
{status: "rejected", reason: "promise 2"},
]
Example 3: Mix of Resolved and Rejected Promises
In the following example, we create an array of three promises, where two of them resolve after a specific amount of time, and one of them rejects. We use Promise.allSettled to wait for all promises to settle.
const promises = [
Promise.resolve("promise 1"),
Promise.reject("promise 2"),
Promise.resolve("promise 3"),
];
Promise.allSettled(promises)
.then((results) => {
console.log(results);
})
The output will be an array of three objects that represent the status of each promise:
[
{status: "fulfilled", value: "promise 1"},
{status: "rejected", reason: "promise 2"},
{status: "fulfilled", value: "promise 3"},
]
Conclusion
Promise.allSettled is a fantastic addition to the Promise API, allowing us to wait for multiple promises to settle and return a detailed status for each promise.
This feature is available natively in modern browsers, and you can start using it today. However, if you need to support older browsers, you may need to use a polyfill or transpile your code using a tool like Babel.
With Promise.allSettled, you can easily handle multiple promises and make your code more efficient and reliable. We hope this article has helped you understand how Promise.allSettled works and its benefits.
here are some more details about the topics we covered:
Promises:
Promises are a way to handle asynchronous operations in JavaScript. They allow you to execute code that takes an indeterminate amount of time, such as fetching data from an API or reading a file, without blocking the main thread.
A Promise is an object that represents the future result of an asynchronous operation. It has three states:
- Pending: The initial state, before the operation completes.
- Fulfilled: The operation completed successfully, and the promise has a value.
- Rejected: The operation failed, and the promise has a reason.
You can create a Promise using the constructor function:
const promise = new Promise((resolve, reject) => {
//...
});
The function passed as an argument to the constructor takes two parameters, resolve and reject. You call resolve with a value when the operation completes successfully, and reject with a reason when the operation fails.
You can use .then() and .catch() methods to handle the resolution or rejection of a promise, or .finally() to execute a code block after the promise is settled:
promise
.then((value) => {
// handle fulfilled promise
})
.catch((reason) => {
// handle rejected promise
})
.finally(() => {
// execute code after the promise is settled, regardless of its state
})
Async/await:
Async/await is a feature introduced in ES2017 that allows you to write asynchronous code in a synchronous style, without callbacks or Promise chains. It’s built on top of Promises and uses the async and await keywords.
The async keyword before a function declaration makes the function return a Promise, and it allows you to use the await keyword inside the function:
async function getData() {
const response = await fetch('https://example.com/data');
const data = await response.json();
return data;
}
The await keyword before a Promise pauses the execution of the function until the Promise is settled, and returns the fulfilled value or throws an error if the Promise is rejected.
You can then call the async function and use .then() and .catch() methods to handle the resolution or rejection of the returned Promise:
getData()
.then((data) => {
// handle fulfilled promise
})
.catch((error) => {
// handle rejected promise
})
TypeScript:
TypeScript is a superset of JavaScript that adds optional static typing, as well as several other features like classes, interfaces, enums, and namespaces.
You write TypeScript code in .ts files, and then use the TypeScript compiler (tsc) to compile the code to JavaScript that can run on any browser or environment.
TypeScript enhances the development experience by catching type-related errors at compile-time instead of run-time, improving the maintainability and reliability of your code, especially in large projects.
Here’s an example of a TypeScript function that takes a string as a parameter and returns its length:
function getStringLength(str: string): number {
return str.length;
}
The type annotation after the parameter name defines the expected type of the parameter, and the return type annotation defines the expected type of the return value. If you pass a value of a different type, the TypeScript compiler will flag an error.
Conclusion:
Promises, async/await, and TypeScript are powerful tools that can help you write better and more reliable code. They allow you to handle asynchronous operations easily, catch errors early, and write code with better documentation and maintainability.
I hope this additional information has helped deepen your understanding of these topics.
Popular questions
-
What is Promise.allSettled in TypeScript?
Answer: Promise.allSettled is a new addition to the Promise API in ECMAScript 2020 that allows you to wait for multiple promises to resolve or reject, and then returns an array of objects that contains information about the status of each promise. -
How does Promise.allSettled work?
Answer: Promise.allSettled takes an iterable of Promise objects and returns a promise that resolves with an array of objects representing the status of each promise. Each object contains a status property with a string value of "fulfilled" or "rejected", and a value or reason property depending on the promise status. -
What's the difference between Promise.all and Promise.allSettled?
Answer: Promise.all waits for all promises to resolve or rejects if one of them rejects, while Promise.allSettled waits for all promises to resolve or reject and returns an array of objects representing the status of each promise. -
Can you give an example of using Promise.allSettled?
Answer:
const promises = [
Promise.resolve("promise 1"),
Promise.reject("promise 2"),
Promise.resolve("promise 3"),
];
Promise.allSettled(promises)
.then((results) => {
console.log(results);
})
The output will be an array of three objects that represent the status of each promise:
[
{status: "fulfilled", value: "promise 1"},
{status: "rejected", reason: "promise 2"},
{status: "fulfilled", value: "promise 3"},
]
- How can TypeScript benefit from using Promise.allSettled?
Answer: TypeScript's static type checking can help catch potential errors when handling the objects returned by Promise.allSettled. The returned array of objects can be typed using an interface to define the expected properties, making the code more maintainable and less error-prone.
Tag
Promisetypescript