惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
P
Privacy & Cybersecurity Law Blog
H
Help Net Security
云风的 BLOG
云风的 BLOG
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
Arctic Wolf
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
The Register - Security
The Register - Security
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
PCI Perspectives
PCI Perspectives
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
A
About on SuperTechFans
W
WeLiveSecurity
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Check Point Blog
Y
Y Combinator Blog
月光博客
月光博客
Scott Helme
Scott Helme
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
U
Unit 42
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Threatpost
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Google Online Security Blog
Google Online Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cisco Talos Blog
Cisco Talos Blog
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 司徒正美

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Use Promise.allSettled()
Dmitri Pavlutin · 2021-08-03 · via Dmitri Pavlutin Blog

Promise.allSettled(promises) is a helper function that runs promises in parallel and aggregates the settled statuses (either fulfilled or rejected) into a result array.

Let's see how Promise.allSettled() works.

1. Promise.allSettled()

Promise.allSettled() is useful to perform independent async operations in parallel, and collect the result of these operations.

The function accepts an array (or generally an iterable) of promises as an argument:


const statusesPromise = Promise.allSettled(promises);


When all input promises are being fulfilled or rejected, in parallel, statusesPromise resolves to an array having their statuses:

  1. { status: 'fulfilled', value: value } — if the corresponding promise has fulfilled
  2. Or { status: 'rejected', reason: reason } — if the corresponding promise has rejected

Promise.allSettled() in JavaScript

After all input promises are being resolved, you can extract their statuses using a then-able syntax:


statusesPromise.then(statuses => {

statuses; // [{ status: '...', value: '...' }, ...]

});


or using an async/await syntax:


const statuses = await statusesPromise;

statuses; // [{ status: '...', value: '...' }, ...]


The promise returned by Promise.allSettled() always fulfills with an array of statuses, no matter if some (or even all!) input promises are rejected.

2. Fetching fruits and vegetables

Before diving into Promise.allSettle(), let's define 2 simple helper functions.

First, resolveTimeout(value, delay) — returns a promise that fulfills with value after passing delay time:


function resolveTimeout(value, delay) {

return new Promise(

resolve => setTimeout(() => resolve(value), delay)

);

}


Second, rejectTimeout(reason, delay) — returns a promise that rejects with reason after passing delay time:


function rejectTimeout(reason, delay) {

return new Promise(

(r, reject) => setTimeout(() => reject(reason), delay)

);

}


Let's use these helper functions to experiment on Promise.allSettled().

2.1 All promises fulfilled

Let's access in parallel the vegetables and fruits available at the local grocerry store. Accessing each list is an asynchornous operation:


const statusesPromise = Promise.allSettled([

resolveTimeout(['potatoes', 'tomatoes'], 1000),

resolveTimeout(['oranges', 'apples'], 1000)

]);

// wait...

const statuses = await statusesPromise;

// after 1 second

console.log(statuses);

// [

// { status: 'fulfilled', value: ['potatoes', 'tomatoes'] },

// { status: 'fulfilled', value: ['oranges', 'apples'] }

// ]


Open the demo.

Promise.allSettled([...]) returns a promise statusesPromise that resolves in 1 second, right after vegetables and fruits were resolved, in parallel.

The promise statusesPromise resolves to an array containing the statuses:

  1. The first item of the array contains the fulfilled status with vegetables: { status: 'fulfilled', value: ['potatoes', 'tomatoes'] }
  2. Same way, the second item is the fulfilled status of fruits: { status: 'fulfilled', value: ['oranges', 'apples'] }.

2.2 One promise rejected

Imagine there are no more fruits at the grocery. In such a case, let's reject the fruits' promise.

How would Promise.allSettled() would work in such a case?


const statusesPromise = Promise.allSettled([

resolveTimeout(['potatoes', 'tomatoes'], 1000),

rejectTimeout(new Error('Out of fruits!'), 1000)

]);

// wait...

const statuses = await statusesPromise;

// after 1 second

console.log(statuses);

// [

// { status: 'fulfilled', value: ['potatoes', 'tomatoes'] },

// { status: 'rejected', reason: Error('Out of fruits!') }

// ]


Open the demo.

The promise returned by Promise.allSettled([...]) resolves to an array of statuses after 1 second:

  1. The first item of the array, since vegetables promise resolved successfully, is { status: 'fulfilled', value: ['potatoes', 'tomatoes'] }
  2. The second item, because fruits promise rejected with an error, is a rejection status: { status: 'rejected', reason: Error('Out of fruits') }.

Even though the second promise in the input array is rejected, the statusesPromise still resolves successfully with an array of statuses.

2.3 All promises rejected

What if the grocerry is out of both vegetables and fruits? In such case both promises reject:


const statusesPromise = Promise.allSettled([

rejectTimeout(new Error('Out of vegetables!'), 1000),

rejectTimeout(new Error('Out of fruits!'), 1000)

]);

// wait...

const statuses = await statusesPromise;

// after 1 second

console.log(statuses);

// [

// { status: 'rejected', reason: Error('Out of vegetables!') },

// { status: 'rejected', reason: Error('Out of fruits!') }

// ]


Open the demo.

In such a case statusesPromise still resolves successfully to an array of statuses. However, the array contains the statuses of rejected promises.

3. Conclusion

Promise.allSettled(promises) lets you run promises in parallel and collect the statuses (either fulfilled or reject) into an aggregate array.

Promise.allSettled(...) works great when you need to perform parallel and independent asynchronous operations and collect all the results even if some async operations could fail.

Challenge: do you know cases when Promise.allSettled() returns a rejected promise? If so, please write a comment below!