Chuyển tới nội dung
Home » Js Promise All Map | Promise.All()

Js Promise All Map | Promise.All()

Does Promise.all Execute in Parallel? - How Promise.all works in JavaScript

Promise.race và Promise.any

Giả sử chúng ta có 2 bài toán như sau, các bạn hãy xem và lựa chọn các dùng nào của Promise nhé.

  • Bài toán 1: có 3 API get thông tin thời tiết và trả về kết quả như nhau, do vậy chỉ cần gọi 1 trong 3 API, cái nào có kết quả là được; không cần gọi tất cả 3 cái. Chúng ta sẽ làm thế nào?
  • Bài toán 2: chức năng upload cần upload file lên 3 server khác nhau và phải đảm bảo việc upload thực hiện thành công trên cả 3 server, nếu 1 trong 3 task fail thì dừng luôn 2 task còn lại.

Để giải quyết 2 bài toán trên, JavaScript cung cấp thêm cho chúng ta 2 function nữa là Promise.race và Promise.any. Promise.race và Promise.any có điểm chung là đều sẽ hoàn thành (resolve) khi 1 trong các promise con được thực hiện xong. Như ví dụ bài toán 1, nếu có 1 API get thông tin thời tiết hoàn thành xong thì nếu dùng Promise.race hoặc Promise.any, 2 API get thông tin thời tiết còn lại sẽ không cần thực hiện nữa.

Điểm khác nhau giữa race và any là ở trường hợp reject: any sẽ chỉ reject khi tất cả các promise con reject (hay không có promise nào trả về resolve); còn race sẽ reject khi chỉ cần 1 promise con reject. Điều này giúp Promise.race giải quyết bài toán thứ 2 ở trên. Khi có 1 trong 3 task upload file lên server thất bại thì sẽ dừng luôn 2 task còn lại.

Chúng ta có thể tổng kết họ hàng nhà Promise.all như sau:

Nhắc lại cú pháp Promise

Trước hết cùng nhắc lại cú pháp Promise cũng như async/await cho các bạn đỡ quên nhé (lưu ý là async/await được thêm vào từ ES8 nhé).

let promise = new Promise(function(resolve, reject) { setTimeout(() => resolve(“done!”), 1000); }); // resolve runs the first function in .then promise.then( result => alert(result), // shows “done!” after 1 second error => alert(error) // doesn’t run );

async function f() { let promise = new Promise((resolve, reject) => { setTimeout(() => resolve(“done!”), 1000) }); let result = await promise; // wait until the promise resolves (*) alert(result); // “done!” }

2 ví dụ trên là cách sử dụng Promise hay async/await để thực hiện việc chờ 1 xử lý bất đồng bộ thực hiện xong, nhận kết quả trả về để thực hiện 1 hành động nào đó – cũng khá dễ hiểu đúng không. Vậy nếu bài toán của chúng ta là cần chờ 2 hành động bất đồng bộ (ví dụ như cần call 2 API lên server) thực hiện xong để lấy kết quả thì sẽ cần làm gì? JS cung cấp cho chúng ta Promise.all.

Does Promise.all Execute in Parallel? - How Promise.all works in JavaScript
Does Promise.all Execute in Parallel? – How Promise.all works in JavaScript

Description

The

Promise.all()

method is one of the promise concurrency methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues.


Promise.all()

will reject immediately upon any of the input promises rejecting. In comparison, the promise returned by

Promise.allSettled()

will wait for all input promises to complete, regardless of whether or not one rejects. Use

allSettled()

if you need the final result of every promise in the input iterable.

What is the promise.all() Method in JavaScript?

JavaScript is an asynchronous language that, most of the time, relies on promises to handle asynchronous operations. Developers face situations where multiple asynchronous tasks need to be executed concurrently, and we need a way to wait until all of them are completed before proceeding. This is where the Promise.all in JavaScript comes into play. In this blog, let us explore what js Promise.all is, its syntax and usage examples, and address common questions such as its differences from Promise. Race, handling non-promise values, managing promise rejections, compatibility, and interplay with async/await.

Promise.all in javaScript can work in the following way-

  1. All or Nothing: Promise.all() waits for all promises in the iterable to settle, meaning they either all resolve or at least one rejects.
  2. Single Promise Result: It returns a single promise that fulfills with an array of results when all promises in the iterable are fulfilled. The order of the results corresponds to the order of the promises in the iterable.
  3. First Rejection: If any promise in the iterable is rejected, the whole Promise.all() is rejected with the reason of the first rejected promise. Subsequent rejections are ignored.

Syntax

The syntax of js Promise.all is relatively straightforward:

Promise.all(iterable);

Here, iterable is an array or any iterable object containing promises. The Promise.all method returns a single promise that resolves when all the promises in the iterable have been resolved or rejected with the reason of the first promise that was rejected.

Promise.all() Function in JavaScript - Aggregate multiple promises!
Promise.all() Function in JavaScript – Aggregate multiple promises!

Syntax


Promise.all(iterable)

Parameters

Return value

A

Promise

that is:

  • Already fulfilled, if the

    iterable

    passed is empty.
  • Asynchronously fulfilled, when all the promises in the given

    iterable

    fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the

    iterable

    passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled.
  • Asynchronously rejected, when any of the promises in the given

    iterable

    rejects. The rejection reason is the rejection reason of the first promise that was rejected.

Wait for array.map iterations in Promise.all [duplicate]

Solution 1:

you can do something like this


const fruitsToGet = ['apple', 'grape', 'pear'] const mapLoop = async () => { console.log('Start') const promises = await fruitsToGet.map(async fruit => { const numFruit = new Promise((resolve, reject) => { setTimeout(() => resolve(fruit), 1000) }); return numFruit }) const numFruits = await Promise.all(promises) console.log(numFruits) console.log('End') } mapLoop();

results


Start ["apple", "grape", "pear"] End

source demo

Solution 2:

Try with

flatMap

:


await Promise.all( customers.flatMap(async (customer) => { return customer.items.map(async (item) => {

Rather than giving back a nested array of Promises, the output will be a consolidated array of Promises that aligns with the expectation of

Promise.all

.

It’s unclear from your inquiry whether the grouping of items per customer should be maintained. If it is essential, please be aware that this solution alters the data structure to a flattened list, causing the loss of grouping. To preserve the grouping, consider incorporating some

customerId

into your

item

or try the suggestion provided by @blex in the comments.

16.15: Promise.all() - Topics of JavaScript/ES6
16.15: Promise.all() – Topics of JavaScript/ES6

Javascript


async


function


handlePromises(promises) {


try


const results = await Promise.all(promises);


console.log(


'Successful results:'


, results);


catch


(error) {


console.error(


'Error occurred:'


, error);


function


fetchData() {


return


new


Promise((resolve) =>


setTimeout(() => resolve(


'Data Fetched'


), 1000));


function


saveData() {


return


new


Promise((resolve) =>


setTimeout(() => resolve(


'Data Saved'


), 500));


const promises = [fetchData(), saveData()];


handlePromises(promises);

Output:

Successful results: [ ‘Data Fetched’, ‘Data Saved’ ]

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!

Last Updated :
08 Nov, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Example of JavaScript Promises that Rely on Each Other

More often than not when making asynchronous operations, in real-world apps. such as http requests that return some data from a server, you would need to make other subsequent requests that rely to each other.

For example, let’s presume, we have the following method for getting a bunch of product categories

// First promise returns an array after a delay

js
const getProducts = () => {
return new Promise((resolve, reject) => {
return setTimeout(
() => resolve([{ id: 'product1' }, { id: 'product2' }, { id: 'product3'}, { id: 'product4'}]),
1000
)
})
}

We use the

setTimeout

method to resolve the promise with an array of products after one second to simulate a real http request which would normally take some time to return.

After fetching the products, we’ll need to get the ID of each product with code similar to this:


// this promise depends on the result of the previous promise const getProductId = (category) => { return new Promise((resolve, reject) => { return setTimeout(() => resolve(category.id), 1000) }) }

We’ll also need a third promise that depends on the second promise:


const capitalizeId = (id) => { return new Promise((resolve, reject) => { return setTimeout(() => resolve(id.toUpperCase()), 700) }) }

The Dangers Of Promise.all()
The Dangers Of Promise.all()

Using .then() and .catch() Method

The .then() method can be used to define what should happen when a Promise successfully resolves, allowing you to specify the next steps in your code. The .catch() method can be utilized when a Promise encounters an error or is rejected, .catch() is employed to handle the error gracefully, letting you manage and log the error that occurred.

Syntax

const tasks = [processData(), saveData(), fetchData()];Promise.all(tasks) .then((completedTasks) => { // All tasks completed successfully, handle the results here }) .catch((error) => { // An error occurred while performing the tasks, handle it here });

Example: In this example, we can handle errors by chaining .then() and .catch() methods to your Promise.all call.

Kết bài

Như vậy chúng ta đã đi qua hết được các phương thức xử lý bất đồng bộ Promise.all cùng cách sử dụng chúng trong từng bài toán cụ thể. Trong thực tế dự án sẽ có nhiều trường hợp các bạn sẽ vận dụng kết hợp các function khác nhau, có thể là Promise.all trong Promise.all chẳng hạn. Vì thế hãy nắm vững cách case sử dụng từng function trên nhé. Hy vọng bài viết của mình hữu ích dành cho các bạn.

Tác giả: Phạm Minh Khoa

Xem thêm:

  • Top 10 câu hỏi phỏng vấn JavaScript cực chi tiết
  • Top 5 tips and tricks hot nhất của JavaScript năm 2023
  • 9 câu hỏi lắt léo về Promise

Tìm việc làm IT mới nhất trên TopDev

JavaScript Promise.all() and the Event Loop Explained - Let's Clarify a Previous Video
JavaScript Promise.all() and the Event Loop Explained – Let’s Clarify a Previous Video

Combining And Resolving all Promises with Promise.all(), map() and Async/Await

So instead of using the for loop with the

async/await

syntax, we need to use the

Promise.all()

and

map()

methods with

async/await

as follows:


const capitalizeProductsIds = async () => { const products = await getProducts() Promise.all( products.map(async (product) => { const productId = await getProductId(product); console.log(productId); const capitalizedId = await capitalizeId(productId) console.log(capitalizedId); }) ) console.log(products); } capitalizeProductsIds();

This is the output:


(4) [{…}, {…}, {…}, {…}] product1 product2 product3 product4 PRODUCT1 PRODUCT2 PRODUCT3 PRODUCT4

So the first promise will be resolved then all the promises returned from the

getProductId()

for each product and then finally all the promises returned from

capitalizeId()

for each ID returned from the previous promises.

According to MDN:

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input’s promises have resolved, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.

  • Author: Ahmed Bouchefra Follow @ahmedbouchefra
  • Date:

Related posts

Star

You must be signed in to star a gist

A sample Promise.all in map

// Function to fetch Github info of a user.
const fetchGithubInfo = async (url) => {
console.log(`Fetching ${url}`)
const githubInfo = await axios(url) // API call to get user info from Github.
return {
name: githubInfo.data.name,
bio: githubInfo.data.bio,
repos: githubInfo.data.public_repos
// Iterates all users and returns their Github info.
const fetchUserInfo = async (names) => {
const requests = names.map((name) => {
const url = `https://api.github.com/users/${name}`
return fetchGithubInfo(url) // Async function that fetches the user info.
.then((a) => {
return a // Returns the user info.
})
})
return Promise.all(requests) // Waiting for all the requests to get resolved.
fetchUserInfo([‘sindresorhus’, ‘yyx990803’, ‘gaearon’])
.then(a => console.log(JSON.stringify(a)))
/*
Output:
[{
“name”: “Sindre Sorhus”,
“bio”: “Full-Time Open-Sourcerer ·· Maker ·· Into Swift and Node.js “,
“repos”: 996
}, {
“name”: “Evan You”,
“bio”: “Creator of @vuejs, previously @meteor & @google”,
“repos”: 151
}, {
“name”: “Dan Abramov”,
“bio”: “Working on @reactjs. Co-author of Redux and Create React App. Building tools for humans.”,
“repos”: 232
}]
*/

Promise.all()

The

Promise.all()

static method takes an iterable of promises as input and returns a single

Promise

. This returned promise fulfills when all of the input’s promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input’s promises rejects, with this first rejection reason.

1 Answer

Steven Parker

228,948 Points

The Promise.all() static method converts the array of promises into a single Promise. The new promise is resolved only when all of the individual promises given to it have resolved, or is rejected when any one of them rejects.

When successful, it returns an array of all the individual fulfillment values.

For more details, see the MDN page on Promise.all().

In this article, we will see how to handle errors with promise.all( ) function. When working with Promise. all in JavaScript, it’s essential to handle errors properly to ensure your application’s robustness and reliability. Promise.all is all or nothing. It resolves once all promises in the array are resolved, or rejected as soon as one of them is rejected. In other words, it either resolves with an array of all resolved values or rejects with a single error. If any of the promises within the array is rejected, the Promise.all itself will reject. Here’s how you can handle errors in Promise. all.

JavaScript Promise.all
JavaScript Promise.all

Description

The

Promise.all()

method is one of the promise concurrency methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of whom we want to fulfill before the code execution continues.


Promise.all()

will reject immediately upon any of the input promises rejecting. In comparison, the promise returned by

Promise.allSettled()

will wait for all input promises to complete, regardless of whether or not one rejects. Use

allSettled()

if you need the final result of every promise in the input iterable.

Promise.all với map()

Một bài toán cũng hay gặp với Promise.all là việc sử dụng nó kết với với map nhằm tạo ra 1 group các xử lý bất đồng bộ theo mảng đầu vào. Chẳng hạn như bạn cần gửi email cho n users có sẵn trong 1 mảng dữ liệu; lúc này chúng ta có thể sử dụng hàm map() để tạo ra mảng promise con làm tham số đầu vào cho Promise.all. Ví dụ như dưới đây:

const timeOut = (t) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(`Completed in ${t}`); }, t); }); }; const durations = [1000, 2000, 3000]; Promise.all(durations.map((duration) => timeOut(duration))).then((response) => console.log(response) );

JavaScript Promises  -- Tutorial for Beginners
JavaScript Promises — Tutorial for Beginners

Combining And Resolving all Promises with For Loop and Async/Await

Now, how to combine all these promises to get the products and capitalize their IDs?

Since the first, returns an array, we can wait for it to resolve and iterate over the array and run the other two promises subsequently i.e for each array item, we wait for the

getProductId

promise to be resolved then call the

capitalizeId

promise as follows:


const capitalizeProductsIds = async () => { const products = await getProducts() for (let product of products) { const productId = await getProductId(product); console.log(productId); const capitalizedId = await capitalizeId(productId); console.log(capitalizedId); } console.log(products); } capitalizeProductsIds()

Combining the

async/await

syntax with the

for..of

loop will give us the following output


product1 PRODUCT1 product2 PRODUCT2 product3 PRODUCT3 product4 PRODUCT4 (4) [{…}, {…}, {…}, {…}]

That’s not the behavior that we are really looking to implement but instead we want to execute the first promise and wait for it to complete, then the second promise and finally the third promise when the second is fully completed.

Conclusion

Promise.all in JavaScript is a useful tool that is used for handling multiple asynchronous operations in JavaScript. This tool simplifies the code and makes it more readable and easy for the coders. The js Promise.all method proves to be a valuable asset in situations where multiple asynchronous operations need to be handled constantly. Promise.all syntax and ability to streamline code make it a preferred choice for developers who want to enhance the efficiency of their applications.

If you are looking to enhance your software development skills further, we would highly recommend you to check Simplilearn’s Professional Certificate Program in Full Stack Web Development – MERN. This course can help you hone the right skills and make you job-ready.

If you have any questions or queries, feel free to post them in the comments section below. Our team will get back to you at the earliest.

Sơ lược vòng đời của Event loop callback promise async await trong Javascript qua chuyện tăng lương
Sơ lược vòng đời của Event loop callback promise async await trong Javascript qua chuyện tăng lương

Understanding Promise.all and Array.map()

Solution 1:

To enable simultaneous requests, it is recommended to provide an array of promises to

Promise.all()

.

Create a map response for each API and wait for its array of promises using

Promise.all()

. Subsequently, await an external call while also waiting for all internal calls with

Promise.all()

.


const response = await getFirstData() // returns an array const [secondResult, thirdResult, fourthResult] = await Promise.all( [secondApiRequest, thirdApiRequest, fourthApiRequest] .map(api => Promise.all(response.map(api))) )

Solution 2:

With this feature, you can execute multiple requests simultaneously and collect their outcomes in their respective variables.


const response = await getFirstData(); // returns an array const [secondResult, thirdResult, fourthResult] = await Promise.all([ Promise.all(response.map(item => secondApiRequest()), Promise.all(response.map(item => thirdApiRequest()), Promise.all(response.map(item => fourthApiRequest()) ]);

Examples

Using Promise.all()


Promise.all

waits for all fulfillments (or the first rejection).


const p1 = Promise.resolve(3); const p2 = 1337; const p3 = new Promise((resolve, reject) => { setTimeout(() => { resolve("foo"); }, 100); }); Promise.all([p1, p2, p3]).then((values) => { console.log(values); // [3, 1337, "foo"] });

If the

iterable

contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled):


// All values are non-promises, so the returned promise gets fulfilled const p = Promise.all([1, 2, 3]); // The only input promise is already fulfilled, // so the returned promise gets fulfilled const p2 = Promise.all([1, 2, 3, Promise.resolve(444)]); // One (and the only) input promise is rejected, // so the returned promise gets rejected const p3 = Promise.all([1, 2, 3, Promise.reject(555)]); // Using setTimeout, we can execute code after the queue is empty setTimeout(() => { console.log(p); console.log(p2); console.log(p3); }); // Logs: // Promise {

: "fulfilled",

: Array[3] } // Promise {

: "fulfilled",

: Array[4] } // Promise {

: "rejected",

: 555 }






Asynchronicity or synchronicity of Promise.all

This following example demonstrates the asynchronicity of

Promise.all

when a non-empty

iterable

is passed:


// Passing an array of promises that are already resolved, // to trigger Promise.all as soon as possible const resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; const p = Promise.all(resolvedPromisesArray); // Immediately logging the value of p console.log(p); // Using setTimeout, we can execute code after the queue is empty setTimeout(() => { console.log("the queue is now empty"); console.log(p); }); // Logs, in order: // Promise {

: "pending" } // the queue is now empty // Promise {

: "fulfilled",

: Array[2] }



The same thing happens if

Promise.all

rejects:


const mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)]; const p = Promise.all(mixedPromisesArray); console.log(p); setTimeout(() => { console.log("the queue is now empty"); console.log(p); }); // Logs: // Promise {

: "pending" } // the queue is now empty // Promise {

: "rejected",

: 44 }




Promise.all

resolves synchronously if and only if the

iterable

passed is empty:


const p = Promise.all([]); // Will be immediately resolved const p2 = Promise.all([1337, "hi"]); // Non-promise values are ignored, but the evaluation is done asynchronously console.log(p); console.log(p2); setTimeout(() => { console.log("the queue is now empty"); console.log(p2); }); // Logs: // Promise {

: "fulfilled",

: Array[0] } // Promise {

: "pending" } // the queue is now empty // Promise {

: "fulfilled",

: Array[2] }





Using Promise.all() with async functions

Within async functions, it’s very common to “over-await” your code. For example, given the following functions:


function promptForDishChoice() { return new Promise((resolve, reject) => { const dialog = document.createElement("dialog"); dialog.innerHTML = `

What would you like to eat?

  • `; dialog.addEventListener("close", () => { if (dialog.returnValue === "ok") { resolve(dialog.querySelector("select").value); } else { reject(new Error("User cancelled dialog")); } }); document.body.appendChild(dialog); dialog.showModal(); }); } async function fetchPrices() { const response = await fetch("/prices"); return await response.json(); }

    You may write a function like this:


    async function getPrice() { const choice = await promptForDishChoice(); const prices = await fetchPrices(); return prices[choice]; }

    However, note that the execution of

    promptForDishChoice

    and

    fetchPrices

    don’t depend on the result of each other. While the user is choosing their dish, it’s fine for the prices to be fetched in the background, but in the code above, the

    await

    operator causes the async function to pause until the choice is made, and then again until the prices are fetched. We can use

    Promise.all

    to run them concurrently, so that the user doesn’t have to wait for the prices to be fetched before the result is given:


    async function getPrice() { const [choice, prices] = await Promise.all([ promptForDishChoice(), fetchPrices(), ]); return prices[choice]; }


    Promise.all

    is the best choice of concurrency method here, because error handling is intuitive — if any of the promises reject, the result is no longer available, so the whole

    await

    expression throws.


    Promise.all

    accepts an iterable of promises, so if you are using it to run several async functions concurrently, you need to call the async functions and use the returned promises. Directly passing the functions to

    Promise.all

    does not work, since they are not promises.


    async function getPrice() { const [choice, prices] = await Promise.all([ promptForDishChoice, fetchPrices, ]); // `choice` and `prices` are still the original async functions; // Promise.all() does nothing to non-promises }

    Promise.all fail-fast behavior


    Promise.all

    is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then

    Promise.all

    will reject immediately.


    const p1 = new Promise((resolve, reject) => { setTimeout(() => resolve("one"), 1000); }); const p2 = new Promise((resolve, reject) => { setTimeout(() => resolve("two"), 2000); }); const p3 = new Promise((resolve, reject) => { setTimeout(() => resolve("three"), 3000); }); const p4 = new Promise((resolve, reject) => { setTimeout(() => resolve("four"), 4000); }); const p5 = new Promise((resolve, reject) => { reject(new Error("reject")); }); // Using .catch: Promise.all([p1, p2, p3, p4, p5]) .then((values) => { console.log(values); }) .catch((error) => { console.error(error.message); }); // Logs: // "reject"

    It is possible to change this behavior by handling possible rejections:


    const p1 = new Promise((resolve, reject) => { setTimeout(() => resolve("p1_delayed_resolution"), 1000); }); const p2 = new Promise((resolve, reject) => { reject(new Error("p2_immediate_rejection")); }); Promise.all([p1.catch((error) => error), p2.catch((error) => error)]).then( (values) => { console.log(values[0]); // "p1_delayed_resolution" console.error(values[1]); // "Error: p2_immediate_rejection" }, );

    JavaScript map() method in 7 minutes! 🗺
    JavaScript map() method in 7 minutes! 🗺

    FAQs

    What is the difference between Promise.all and Promise.race?

    While Promise.all in JavaScript waits for all promises in the iterable to be resolved or rejected Promise.race returns as soon as one of the promises in the iterable is settled. It’s a race to see which promise settles first. This can be useful in scenarios where you only need the result of the first settled promise.

    Consider the following example:

    Syntax:


    const promise1 = new Promise((resolve) => setTimeout(resolve, 100, 'First')); const promise2 = new Promise((resolve, reject) => setTimeout(reject, 200, 'Second')); Promise.all([promise1, promise2]) .then((values) => { console.log(values); }) .catch((error) => { console.error(error); // Output: Second }); Promise.race([promise1, promise2]) .then((value) => { console.log(value); // Output: First }) .catch((error) => { console.error(error); });

    In this example, Promise.all() catches the rejection of promise2 and logs the error while Promise.race() resolves with the value of the first fulfilled promise, which is promise1.

    Can I use Promise.all with non-promise values?

    Yes, Promise.all in JavaScript is flexible enough to handle a mix of promises and non-promise values in the iterable. Non-promise values are treated as already fulfilled promises. The resulting promise from Promise.all() will be fulfilled with an array of all the values, whether they are promises or not.


    const promise1 = new Promise((resolve) => setTimeout(resolve, 100, 'First')); Promise.all([promise1, 'Non-promise value', 42]) .then((values) => { console.log(values); // Output: ['First', 'Non-promise value', 42] }) .catch((error) => { console.error(error); });

    How can I handle promise rejections with Promise.all()?

    Handling promise rejections with Promise.all() involves using the .catch() method on the returned promise. This method is invoked if any of the input promises are rejected.


    const promise1 = new Promise((resolve, reject) => setTimeout(reject, 100, 'Error')); Promise.all([promise1]) .then((values) => { console.log(values); }) .catch((error) => { console.error(error); // Output: Error });

    In this example, the .catch() block captures the rejection reason of promise1.

    Is Promise.all Supported in All JavaScript Environments?

    Promise.all in JavaScript is a standard ECMAScript 6 (ES6) feature and is widely supported in modern JavaScript environments. Also, verifying the compatibility with the specific environments your application targets is essential. Generally, all major browsers and Node.js support Promise.all().

    However, anyone working in an environment that does not support ES6 features may face compatibility issues. In such cases, consider using a transpiler like Babel to convert your code to a compatible version.

    Can I use async/await with Promise.all()?

    Yes, Combining async/await with Promise.all in JavaScript enhances the readability of asynchronous code. The async/await syntax allows you to work with promises more synchronously.


    async function fetch data() { const promise1 = fetch('https://api.example.com/data1'); const promise2 = fetch('https://api.example.com/data2'); const promise3 = fetch('https://api.example.com/data3'); try { const responses = await Promise.all([promise1, promise2, promise3]); const data = await Promise.all(responses.map((response) => response.json())); console.log(data); } catch (error) { console.error(error); } } fetchData();

    In this example, the fetchData function asynchronously fetches data from multiple endpoints using fetch and js Promise.all(). The await keyword simplifies the handling of promises, making the code cleaner and more readable.

    Promise.all()

    The

    Promise.all()

    static method takes an iterable of promises as input and returns a single

    Promise

    . This returned promise fulfills when all of the input’s promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input’s promises rejects, with this first rejection reason.

    JavaScript Promise.all() Method Examples

    Let us look at some practical examples to understand how Promise.all in JavaScript works in different scenarios.

    Example 1: Basic usage

    Syntax:


    const promise1 = new Promise(resolve => setTimeout(() => resolve('One'), 1000)); const promise2 = new Promise(resolve => setTimeout(() => resolve('Two'), 2000)); const promise3 = new Promise(resolve => setTimeout(() => resolve('Three'), 3000)); Promise.all([promise1, promise2, promise3]) .then(values => console.log(values)) .catch(error => console.error(error));

    In this example, we create three promises that resolve after different time intervals. The js Promise.all method is used to wait for all promises to resolve, and then the values are logged. If any promise.all in javascript is rejected, the catch block captures the first rejection.

    Example 2: Handling Non-Promise values


    const promise1 = Promise.resolve(1); const promise2 = 'Not a promise'; const promise3 = new Promise(resolve => setTimeout(() => resolve('Three'), 1000)); Promise.all([promise1, promise2, promise3]) .then(values => console.log(values)) .catch(error => console.error(error));

    Here, promise2 is not a promise, but Promise.all() still works. The non-promise values are treated as resolved promises, allowing the method to handle a mix of promises and non-promise values.

    ASYNC JavaScript trong 30 phút (CALLBACK, PROMISES, ASYNC AWAIT)
    ASYNC JavaScript trong 30 phút (CALLBACK, PROMISES, ASYNC AWAIT)

    Promise.allSettled

    Promise.allSettled([ Promise.reject(“This failed.”), Promise.reject(“This failed too.”), Promise.resolve(“Ok I did it.”), Promise.reject(“Oopps, error is coming.”), ]).then((res) => { console.log(`Here’s the result: `, res); });

    Kết quả trả về:

    [ { status: “rejected”, reason: “This failed.” }, { status: “rejected”, reason: “This failed too.” }, { status: “fulfilled”, value: “Ok I did it.” }, { status: “rejected”, reason: “Oopps, error is coming.” }, ];

    JavaScript cung cấp cho chúng ta Promise.allSettled để giải quyết vấn đề đầu tiên của Promise.all. Promise.allSettled trả về 1 Promise mới mà ở đó nó sẽ chờ tất cả các task con thực hiện xong, không kể có hoàn thành (resolve) hay bị reject. Kết quả trả về là 1 mảng theo thứ tự các Promise con truyền vào, mỗi object chứa status (trạng thái) của promise cùng giá trị trả về value hay reason (lí do) khi bị reject. Tất nhiên Promise.allSettled sẽ cần nhiều thời gian xử lý hơn so với Promise.all, tuy nhiên nó đảm bảo tất cả Promise được thực hiện.

    Await promise.all How to use async/await with map and Promise.all

    Initially, I faced difficulties in utilizing the map function alongside async and await. However, reacquainting myself with promise handling proved to be the solution. Once I grasped this, I found the syntax to be remarkably clear and easy to comprehend.

    The async and await syntax in JavaScript was introduced in ES2017 and is a great improvement over the pyramid of promises and thens. It allows for shorter and easier to understand code, similar to how promises are an improvement over callback hell. More detailed explanations of async and await can be found on MDN, Javascript.Info, and from Dr. Axel R. Additionally, the JavaScript Jabber episode is also a valuable resource.

    In JavaScript, there is no

    await all

    to retrieve multiple data from different requests simultaneously. However,

    Promises.all()

    can solve this issue. By using Promises.all(), a group of promises can be gathered and combined into a single promise. Only when all the inner promises are resolved successfully, a resolved promise with all the inner promises as resolved is returned. To ensure efficiency, if any of the inner promises are rejected, Promise.all() will also reject.

    The crucial aspect of Promise.all() is that it transforms an array of promises into a solitary promise which, assuming success, resolves to the desired array. The specifics are not as significant.

    After struggling for a considerable period, I finally managed to overcome the obstacle. The following code is what eventually worked for me, and I trust it will aid in clarifying the matter.

    Assuming you receive an array of REST endpoint URLs that contain the information you need, after hitting a REST endpoint. Let’s say you want to retrieve details of R2-D2’s movies from the Star Wars API, but the SWAPI GraphQL is not an option. As network fetching is an asynchronous process, the use of callbacks, promises, or async/await is necessary. Since R2-D2 appeared in multiple movies, multiple network requests will be required to get all the necessary data.

    To begin with, we need to set up our environment. Our attention should be directed towards the specific functionality we’re currently developing. For this purpose, we will utilize Node.js on the command line. However, fetch is unavailable in Node.js by default. Therefore, we’ll have to acquire it through npm or yarn installation.


    npm install node-fetch --save-dev

    or


    yarn add node-fetch --dev

    When working with async/await, it’s important to note that the await keyword can only be used inside an async function. While this may not be an issue in a larger program where you can simply add the async keyword to the function, it can be more challenging when working in a scratch file and wanting to separate from the surrounding context. A workaround for this is to utilize an immediately invoked function expression to isolate the desired code. As experienced Javascript programmers, we know how to overcome this limitation.


    // prettier-ignore const fetch = require('node-fetch') // prettier-ignore (async () => { try { let characterResponse = await fetch('http://swapi.co/api/people/2/') let characterResponseJson = await characterResponse.json() console.log(characterResponseJson) } catch (err) { console.log(err) } } )()

    After successfully implementing the async/await syntax, we can examine the returned response to determine our desired field, which happens to be an array of URLs under the name “films”.


    let films = characterResponseJson.films.map(async filmUrl => { let filmResponse = await fetch(filmUrl) let filmResponseJSON = filmResponse.json() return filmResponseJSON }) console.log(films)

    Executing the code generates an array of promises that are yet to be fulfilled. To enable the awaits within the arrow function to function correctly, it is essential to include the new

    async

    . Failure to specify

    await

    for the fetch operation will result in a collection of rejected promises and error messages that prompt you to handle your promise rejections.

    It’s worth remembering that a

    Promise.all()

    combines multiple promises into one. Therefore, we use this approach to wrap our

    map

    function, benefiting from the convenient syntax available for handling a single promise, which we can

    await

    .


    let characterResponse = await fetch('http://swapi.co/api/people/2/') let characterResponseJson = await characterResponse.json() let films = await Promise.all( characterResponseJson.films.map(async filmUrl => { let filmResponse = await fetch(filmUrl) return filmResponse.json() }) ) console.log(films)

    To make a comparison, the promises code equivalent appears as follows:


    fetch('http://swapi.co/api/people/2/') .then(characterResponse => characterResponse.json()) .then(characterResponseJson => { Promise.all( characterResponseJson.films.map(filmUrl => fetch(filmUrl).then(filmResponse => filmResponse.json()) ) ).then(films => { console.log(films) }) })

    The initial block of

    .then().then()

    is quite understandable to me, almost as much as the async/await syntax. However, once we enter the

    Promise.all()

    , it becomes challenging to follow the promises syntax. The

    console.log

    will be substituted with the action we want to execute on the movies, and the chaining syntax in

    .then

    already has three levels of indentation, making it difficult to comprehend. Clear and straightforward code is easier to comprehend.

    What are JavaScript PROMISES? 🤞
    What are JavaScript PROMISES? 🤞

    Javascript map array promise.all

    Solution:

    To utilize Promise.all, provide an array of Promises you wish to process, including the result of your imageIds.map function. The map function does not require async operations, only a returned promise that Promise.all can manage. For instance, when making network requests for each image id, use the map function as shown in

    return fetch(yourEndPoint + id)

    , and Promise.all will manage the async processing.

    Refer to the documentation on how to use Promise.all in JavaScript at this link – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all.

    Anh em lập trình viên JavaScript chắc không xa lạ gì với Promise hay async/await trong việc xử lý các tác vụ bất đồng độ trong ứng dụng của mình; tuy vậy trong thực tế dự án có nhiều bài toán cần không chỉ 1 Promise và cần handle (xử lý) kết quả trả về trong từng Promise con, lúc này thứ chúng ta cần là Promise.all và 1 vài thứ tốt hơn thế. Bài viết này mình sẽ chia sẻ cùng các bạn cách sử dụng Promise.all trong những bài toán cụ thể ở dự án mình từng trải qua.

    Promise.all

    Promise.all([Promise1, Promise2, Promise3]) .then((result) => { console.log(result); }) .catch((error) => console.log(`Error in promises ${error}`));

    Promise1, Promise2 và Promise3 là những promise, bản thân Promise.all cũng là 1 promise. Vậy nó khác gì với việc chạy riêng lẻ 3 promise từ 1-3 một cách độc lập. Đầu tiên thì trong Promise.all, cả 3 Promise1-3 sẽ được thực hiện đồng thời, không cái nào cần chờ cái nào, vì thế giảm được thời gian chờ đợi và đương nhiên là tăng performance. Tiếp theo chúng ta cần lưu ý, nếu 1 trong 3 Promise1-3 đẩy ra lỗi (reject) thì Promise sẽ ngay lập tức dừng lại và nhảy vào catch chứ không thực hiện tiếp các promise khác. Trong trường hợp các task con thực hiện thành công thì Promise.all cũng sẽ trả về resolve với kết quả là 1 mảng chứa tất cả các resolve của task con.

    Việc làm JavaScript Hồ Chí Minh dành cho bạn!

    Đến đây chúng ta vẫn thấy quen thuộc đúng không, thực tế Promise.all được sử dụng thường xuyên trong các bài toán thực tế dự án. Mặc dù vậy sẽ có 1 số vấn đề khi sử dụng Promise.all như sau:

    • Làm sao để tạo 1 mảng Promise sử dụng map
    • Nếu muốn tất cả các Promise con thực hiện xong mà không bị dừng bị 1 trong các Promise khác thì làm sao?
    • Nếu muốn chỉ 1 trong các Promise con thực hiện xong (resolve) là hủy các Promise còn lại thì làm sao?
    • Nếu muốn chỉ 1 trong các Promise con trả về (bất kể resolve hay reject) là hủy các Promise còn lại thì làm sao?

    Chúng ta cùng đi giải quyết các câu hỏi trên nhé.

    Async JavaScript & Callback Functions -- Tutorial for Beginners
    Async JavaScript & Callback Functions — Tutorial for Beginners

    I have the following code that should add items for customers if they dont already exist. Execution should be in parallel.


    await Promise.all( customers.map(async (customer) => { return customer.items.map(async (item) => { return new Promise(async (resolve) => { const productExists = someArray.some( (arrayValue) => arrayValue === item.id ); if (!productExists) { logger.info( `customer item ${item.id} does not exist, creating...` ); await createCustomerItem(item.id); logger.info(`customer item ${item.id} created.`); someArray.push(item.id); } else { logger.info(`customer item ${item.id} already exists, skipping...`); } resolve(true); }); }); }) ); logger.info(`All items should now be present`);

    The problem is that the execution is not waiting for

    createCustomerItem

    to resolve in the cases of

    !productExists)

    This is the log


    customer item 32310 does not exist, creating... customer item ao does not exist, creating... customer item ute does not exist, creating... All items should not be present customer item ao created. customer item ute created. customer item 32310 created.

    Naturally

    All items should not be present

    should come last.

    When all the items already exist, then the process looks good.

    Promise.all() and map() with Async/Await by Example

    In this quick example, we’ll learn how to use

    Promise.all()

    and

    map()

    with

    Async/Await

    in JavaScript to impelemt certain scenarios that can’t be implemented with for loops with

    async/await

    .

    Javascript


    function


    fetchData() {


    return


    new


    Promise((resolve, reject) => {


    setTimeout(() => {


    resolve(


    'Data 1'


    );


    }, 1000);


    });


    function


    saveData(processedData) {


    return


    new


    Promise((resolve, reject) => {


    setTimeout(() => {


    resolve(`Saved`);


    }, 500);


    });


    const promises = [fetchData(), saveData()];


    Promise.all(promises)


    .then((results) => {


    console.log(


    'All tasks completed successfully:'


    );


    console.log(results);


    })


    catch


    ((error) => {


    console.error(


    'An error occurred:'


    , error);


    });

    Output:

    All tasks completed successfully:[ ‘Data 1’, ‘Saved’ ]

    How To Create Your Own Implementation Of JavaScript Promises
    How To Create Your Own Implementation Of JavaScript Promises

    Using async/await

    Async/await is a programming technique that streamlines asynchronous operations, allowing code to pause and resume tasks .It also simplifies asynchronous programming, by handling tasks one step at a time, enhancing code readability and responsiveness.

    Syntax

    async function executeTasks(tasks) { try { const taskResults = await Promise.all(tasks); // Handle the successful completion of tasks here } catch (taskError) { // Handle errors that occurred during task execution here }}const tasks = [fetchData(), saveData()];executeTasks(tasks);

    Example: In this example, we will implement a code to handle errors by using async/await syntax.

    Browser compatibility

    BCD tables only load in the browser

    I found myself stuck on using the map function with async and await. It took me relearning how to work with promises to figure it out, but once I figured it out, the syntax turned out to be pretty nice and readable.

    JavaScript’s async and await syntax is new as of ES2017. I think the syntax is really neat because it allows me to write shorter, easier to understand code than a pyramid of promises and thens, similar to how promises are an improvement on callback hell. There are more comprehensive explanations of async and await out there, like this one from MDN, from Javascript.Info, and from Dr. Axel R. Here is a JavaScript Jabber episode, super helpful.

    But what happens when you want to get back a bunch of data from a bunch of requests? There is no

    await all

    in JavaScript. That’s where

    Promises.all()

    comes in. Promises.all() collects a bunch of promises, and rolls them up into a single promise. Once all of the inner promises resolve successfully, Promise.all() returns a resolved promise with all of the inner promises as resolved. To make things faster, once any of the inner promises rejects, Promise.all() rejects.

    The main point is that Promise.all() turns an array of promises into a single promise that, if things work, resolves into the array you want. Everything else is just details.

    Somehow, it took me a long time to get unstuck. Here is the code that I finally got working, and hopefully this helps with that explanation.

    Suppose you hit a REST endpoint and get an array of URLs for the REST endpoints which contain what you are ultimately after. For example, you know want to find some information about the movies R2-D2 was in from the Star Wars API. For whatever reason, you can’t use the SWAPI GraphQL instead. We know that fetching from the network is an asynchronous operation, so we will have to use callbacks, promises, or the async and await keywords. Since R2-D2 was in several movies, will have several network calls to get all of them.

    So first, let’s set up. Let’s focus on just the smallest bit of functionality we’re working on, so we’ll use Node.js on the command line. Node.js doesn’t come with fetch, so let’s install it with npm or yarn.


    npm install node-fetch --save-dev

    or


    yarn add node-fetch --dev

    One gotcha with async/await is that an await keyword is only allowed inside an async function. In a real program, you’re probably encapsulated enough so that you can just slap an async keyword on the function you’re using the await keyword in, but inside of a scratch file, we want to abstract away from the enclosing context. But as Javascript programmers, we know how to get around that by wrapping what we want in an instantaneously invoked function expression.


    // prettier-ignore const fetch = require('node-fetch') // prettier-ignore (async () => { try { let characterResponse = await fetch('http://swapi.co/api/people/2/') let characterResponseJson = await characterResponse.json() console.log(characterResponseJson) } catch (err) { console.log(err) } } )()

    So now we have the basic async/await syntax working, and we can inspect the response to see that we want the films field. It is an array of URLs.


    let films = characterResponseJson.films.map(async filmUrl => { let filmResponse = await fetch(filmUrl) let filmResponseJSON = filmResponse.json() return filmResponseJSON }) console.log(films)

    When you run this code, you get an array of pending promises. You need that new

    async

    , otherwise the awaits inside the arrow function won’t work. If you don’t

    await

    for the fetch, you get a bunch of rejected promises, and errors telling you to handle your promise rejections.

    But recall, a

    Promise.all()

    takes an array of promises and wraps them into a single promise. So we wrap our

    map

    function. And we already know some nice syntax for dealing with a single promise. We can

    await

    it.


    let characterResponse = await fetch('http://swapi.co/api/people/2/') let characterResponseJson = await characterResponse.json() let films = await Promise.all( characterResponseJson.films.map(async filmUrl => { let filmResponse = await fetch(filmUrl) return filmResponse.json() }) ) console.log(films)

    For the sake of comparison, the equivalent code in promises looks like:


    fetch('http://swapi.co/api/people/2/') .then(characterResponse => characterResponse.json()) .then(characterResponseJson => { Promise.all( characterResponseJson.films.map(filmUrl => fetch(filmUrl).then(filmResponse => filmResponse.json()) ) ).then(films => { console.log(films) }) })

    For me, the first set of

    .then().then()

    is pretty semantic, I can follow that almost as well as the async/await syntax. But once we’re inside the

    Promise.all()

    , things start getting hard to follow using only the promises syntax. Whatever action we are going to perform on the films will replace the

    console.log

    , and in the

    .then

    chaining syntax, that is already buried 3-levels of indentation deep. Shallow code is easy to understand code.

    Mapping an array of Promise.all in JavaScript: A guide

    To run requests concurrently and obtain their outcomes in designated variables, Solution 2 can be utilized. Promise.all can be employed to process an array of Promises, where imageIds.map function will generate a list of promises that need to be resolved. Promise.all() essentially transforms an array of promises into a single promise that, when successful, resolves into the desired array.

    Callbacks, Promises, Async Await | JavaScript Fetch API Explained
    Callbacks, Promises, Async Await | JavaScript Fetch API Explained

    Welcome to the Treehouse Community

    Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you’re at it, check out some resources Treehouse students have shared here.

    Looking to learn something new?

    Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

    Start your free trial

    Samuel Kleos

    Front End Web Development Techdegree Student 12,719 Points

    Does promise.all() produce an array of objects, or an array-like collection?

    All this promise stuff is quite foreign, but it’s certainly interesting.

    I can understand that every time a request is made to a server, you might need to generate a promise to manipulate the data returned as a promise object with .resolve().

    What I don’t understand is the nature of the data being delivered to resolve() when the Promise.all() method is applied.

    function getProfiles(json) { const profiles = json.people.map( person => { return getJSON(wikiUrl+person.name); }); return Promise.all(profiles); }

    What do promises actually return to the resolve placeholder when Promise.all() is called?

    Examples

    Using Promise.all()


    Promise.all

    waits for all fulfillments (or the first rejection).


    const p1 = Promise.resolve(3); const p2 = 1337; const p3 = new Promise((resolve, reject) => { setTimeout(() => { resolve("foo"); }, 100); }); Promise.all([p1, p2, p3]).then((values) => { console.log(values); // [3, 1337, "foo"] });

    If the

    iterable

    contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled):


    // All values are non-promises, so the returned promise gets fulfilled const p = Promise.all([1, 2, 3]); // The only input promise is already fulfilled, // so the returned promise gets fulfilled const p2 = Promise.all([1, 2, 3, Promise.resolve(444)]); // One (and the only) input promise is rejected, // so the returned promise gets rejected const p3 = Promise.all([1, 2, 3, Promise.reject(555)]); // Using setTimeout, we can execute code after the queue is empty setTimeout(() => { console.log(p); console.log(p2); console.log(p3); }); // Logs: // Promise {

    : "fulfilled",

    : Array[3] } // Promise {

    : "fulfilled",

    : Array[4] } // Promise {

    : "rejected",

    : 555 }






    Asynchronicity or synchronicity of Promise.all

    This following example demonstrates the asynchronicity of

    Promise.all

    when a non-empty

    iterable

    is passed:


    // Passing an array of promises that are already resolved, // to trigger Promise.all as soon as possible const resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; const p = Promise.all(resolvedPromisesArray); // Immediately logging the value of p console.log(p); // Using setTimeout, we can execute code after the queue is empty setTimeout(() => { console.log("the queue is now empty"); console.log(p); }); // Logs, in order: // Promise {

    : "pending" } // the queue is now empty // Promise {

    : "fulfilled",

    : Array[2] }



    The same thing happens if

    Promise.all

    rejects:


    const mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)]; const p = Promise.all(mixedPromisesArray); console.log(p); setTimeout(() => { console.log("the queue is now empty"); console.log(p); }); // Logs: // Promise {

    : "pending" } // the queue is now empty // Promise {

    : "rejected",

    : 44 }




    Promise.all

    resolves synchronously if and only if the

    iterable

    passed is empty:


    const p = Promise.all([]); // Will be immediately resolved const p2 = Promise.all([1337, "hi"]); // Non-promise values are ignored, but the evaluation is done asynchronously console.log(p); console.log(p2); setTimeout(() => { console.log("the queue is now empty"); console.log(p2); }); // Logs: // Promise {

    : "fulfilled",

    : Array[0] } // Promise {

    : "pending" } // the queue is now empty // Promise {

    : "fulfilled",

    : Array[2] }





    Using Promise.all() with async functions

    Within async functions, it’s very common to “over-await” your code. For example, given the following functions:


    function promptForDishChoice() { return new Promise((resolve, reject) => { const dialog = document.createElement("dialog"); dialog.innerHTML = `

    What would you like to eat?

  • `; dialog.addEventListener("close", () => { if (dialog.returnValue === "ok") { resolve(dialog.querySelector("select").value); } else { reject(new Error("User cancelled dialog")); } }); document.body.appendChild(dialog); dialog.showModal(); }); } async function fetchPrices() { const response = await fetch("/prices"); return await response.json(); }

    You may write a function like this:


    async function getPrice() { const choice = await promptForDishChoice(); const prices = await fetchPrices(); return prices[choice]; }

    However, note that the execution of

    promptForDishChoice

    and

    fetchPrices

    don’t depend on the result of each other. While the user is choosing their dish, it’s fine for the prices to be fetched in the background, but in the code above, the

    await

    operator causes the async function to pause until the choice is made, and then again until the prices are fetched. We can use

    Promise.all

    to run them concurrently, so that the user doesn’t have to wait for the prices to be fetched before the result is given:


    async function getPrice() { const [choice, prices] = await Promise.all([ promptForDishChoice(), fetchPrices(), ]); return prices[choice]; }


    Promise.all

    is the best choice of concurrency method here, because error handling is intuitive — if any of the promises reject, the result is no longer available, so the whole

    await

    expression throws.


    Promise.all

    accepts an iterable of promises, so if you are using it to run several async functions concurrently, you need to call the async functions and use the returned promises. Directly passing the functions to

    Promise.all

    does not work, since they are not promises.


    async function getPrice() { const [choice, prices] = await Promise.all([ promptForDishChoice, fetchPrices, ]); // `choice` and `prices` are still the original async functions; // Promise.all() does nothing to non-promises }

    Promise.all fail-fast behavior


    Promise.all

    is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then

    Promise.all

    will reject immediately.


    const p1 = new Promise((resolve, reject) => { setTimeout(() => resolve("one"), 1000); }); const p2 = new Promise((resolve, reject) => { setTimeout(() => resolve("two"), 2000); }); const p3 = new Promise((resolve, reject) => { setTimeout(() => resolve("three"), 3000); }); const p4 = new Promise((resolve, reject) => { setTimeout(() => resolve("four"), 4000); }); const p5 = new Promise((resolve, reject) => { reject(new Error("reject")); }); // Using .catch: Promise.all([p1, p2, p3, p4, p5]) .then((values) => { console.log(values); }) .catch((error) => { console.error(error.message); }); // Logs: // "reject"

    It is possible to change this behavior by handling possible rejections:


    const p1 = new Promise((resolve, reject) => { setTimeout(() => resolve("p1_delayed_resolution"), 1000); }); const p2 = new Promise((resolve, reject) => { reject(new Error("p2_immediate_rejection")); }); Promise.all([p1.catch((error) => error), p2.catch((error) => error)]).then( (values) => { console.log(values[0]); // "p1_delayed_resolution" console.error(values[1]); // "Error: p2_immediate_rejection" }, );

    How Async Javascript works (Callback Hell, Promises, Async Await, Call Stack and more)
    How Async Javascript works (Callback Hell, Promises, Async Await, Call Stack and more)

    Syntax


    Promise.all(iterable)

    Parameters

    Return value

    A

    Promise

    that is:

    • Already fulfilled, if the

      iterable

      passed is empty.
    • Asynchronously fulfilled, when all the promises in the given

      iterable

      fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the

      iterable

      passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled.
    • Asynchronously rejected, when any of the promises in the given

      iterable

      rejects. The rejection reason is the rejection reason of the first promise that was rejected.

    Keywords searched by users: js promise all map

    Javascript - Wikipedia
    Javascript – Wikipedia
    Promise - Javascript | Mdn
    Promise – Javascript | Mdn
    Using A For Loop With Async Or Using .Map() To Return An Array Of Promises  And Then Using Promise.All? : R/Learnjavascript
    Using A For Loop With Async Or Using .Map() To Return An Array Of Promises And Then Using Promise.All? : R/Learnjavascript
    Does Javascript Promise.All() Run In Parallel Or Sequential?
    Does Javascript Promise.All() Run In Parallel Or Sequential?

    See more here: kientrucannam.vn

    Trả lời

    Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *