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

推荐订阅源

G
Google Developers Blog
S
Schneier on Security
The Hacker News
The Hacker News
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
I
Intezer
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Schneier on Security
Schneier on Security
Security Latest
Security Latest
AWS News Blog
AWS News Blog
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog
有赞技术团队
有赞技术团队
博客园 - 叶小钗
The Last Watchdog
The Last Watchdog
O
OpenAI News
月光博客
月光博客
Hacker News: Ask HN
Hacker News: Ask HN
阮一峰的网络日志
阮一峰的网络日志
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Latest news
Latest news
P
Palo Alto Networks Blog
Last Week in AI
Last Week in AI
M
MIT News - Artificial intelligence
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Apple Machine Learning Research
Apple Machine Learning Research
U
Unit 42
PCI Perspectives
PCI Perspectives
博客园 - 聂微东
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
Forbes - Security
Forbes - Security
H
Heimdal Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Troy Hunt's Blog
博客园 - 三生石上(FineUI控件)
Application and Cybersecurity Blog
Application and Cybersecurity Blog
罗磊的独立博客
WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security

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 Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? 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.all()
Dmitri Pavlutin · 2021-07-06 · via Dmitri Pavlutin Blog

A promise is a placeholder for a value that's going to be available sometime later. The promise helps handle asynchronous operations.

JavaScript provides a helper function Promise.all(promisesArrayOrIterable) to handle multiple promises at once, in parallel, and get the results in a single aggregate array. Let's see how it works.

1. Promise.all()

Promise.all() is a built-in helper that accepts an array of promises (or generally an iterable). The function returns a promise from where you can extract promises resolved values using a then-able syntax:


const allPromise = Promise.all([promise1, promise2]);

allPromise.then(values => {

console.log(values); // [resolvedValue1, resolvedValue2]

}).catch(error => {

console.log(error); // rejectReason of any first rejected promise

});


In the case of async/await syntax:


const allPromise = Promise.all([promise1, promise2]);

try {

const values = await allPromise;

console.log(values); // [resolvedValue1, resolvedValue2]

} catch (error) {

console.log(error); // rejectReason of any first rejected promise

}


The interesting part is in the way the promise returned by Promise.all() gets resolved or rejected.

If all promises are resolved successfully, then allPromise fulfills with an array containing fulfilled values of the promises. The order of promises in the array does matter — you'll get the fulfilled values in the same order.

Promise.all() - all fullfilled

But if at least one promise rejects, then allPromise rejects right away (without waiting for the remaining pending promises to resolve) for the same reason.

Promise.all() - one rejects

Let's see some examples.

2. Example: all promises fulfilled

To study how Promise.all() works, I'm going to use 2 helpers — resolveTimeout(value, delay) and rejectTimeout(reason, delay).


function resolveTimeout(value, delay) {

return new Promise(

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

);

}

function rejectTimeout(reason, delay) {

return new Promise(

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

);

}


resolveTimeout(value, delay) returns a promise that fulfills with value after passing delay time.

rejectTimeout(reason, delay), however, returns a promise that rejects with reason (usually an error) after passing delay time.

Let's access, at the same time, the lists of vegetables and fruits available at the local grocery store. Accessing each list is an asynchronous operation:


const allPromise = Promise.all([

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

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

]);

// wait...

const lists = await allPromise;

// after 1 second

console.log(lists);

// [['potatoes', 'tomatoes'], ['oranges', 'apples']]


Open the demo.

const allPromise = Promise.all([...]) returns a new promise allPromise.

const lists = await allPromise awaits 1 second until allPromise fulfills with an array containing the first and second promises fulfill values.

Finally, lists contains the aggregated result: [['potatoes', 'tomatoes'], ['oranges', 'apples']].

Note that the order of the values in the aggregated result corresponds to the order of the promises in the array supplied to Promise.all():


const [resolvedOfPromise1, resolvedOfPromise2] = Promise.all([promise1, promise2])


3. Example: one promise rejects

Now imagine the situation the grocery is out of fruits. Let's reject the fruits promise with an error new Error('Out of fruits!'):


const allPromise = Promise.all([

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

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

]);

try {

// wait...

const lists = await allPromise;

} catch (error) {

// after 1 second

console.log(error.message); // 'Out of fruits!'

}


Open the demo.

In this scenario allPromise = Promise.all([...]) returns, as usual, a promise.

After 1 second the second promise rejects with an error new Error('Out of fruits!'). This makes allPromise reject right away with the same new Error('Out of fruits!').

Even if the vegetables' promise has been fulfilled, Promise.all() doesn't take it into account.

Such behavior of Promise.all([...]) is named fail-fast. If at least one promise in the promises array rejects, then the promise returned by allPromise = Promise.all([...]) rejects too — for the same reason.

4. Conclusion

Promise.all([...]) is a useful helper function that lets you execute asynchronous operations in parallel, using a fail-fast strategy, and aggregate the results into an array.

How often do you use Promise.all()?