📜  javascript promise all - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:06.497000             🧑  作者: Mango

JavaScript Promise.all

When working with Promises in JavaScript, it is sometimes necessary to execute multiple Promises simultaneously and wait for all the results to arrive before moving on to the next step. This is where the Promise.all method comes in handy.

Syntax

The basic syntax of Promise.all is as follows:

Promise.all(iterable);

Here, iterable is an iterable object (such as an array) of Promises to be executed simultaneously.

Usage

Let's say we have two functions getUser and getOrders that retrieve user data and order data respectively. Using Promise.all, we can execute both these functions simultaneously and wait for both Promises to resolve before moving on to the next step:

// Define the two Promises
const userPromise = getUser();
const ordersPromise = getOrders();

// Execute both Promises simultaneously
Promise.all([userPromise, ordersPromise])
  .then(([user, orders]) => {
    // Both Promises have resolved successfully
    console.log(`User: ${user.name}, Orders: ${orders.length}`);
  })
  .catch((error) => {
    // One or more Promises have rejected
    console.error(error);
  });

Here, Promise.all takes an array of Promises as input and returns another Promise that resolves to an array of the respective resolved values of the input Promises. In the then block, we can access these values as an array through destructuring and perform the necessary operations.

If one or more of the input Promises reject, the catch block is executed and we can handle the error accordingly.

Conclusion

Promise.all is a useful method when it comes to executing multiple Promises simultaneously and waiting for all of them to resolve before moving on to the next step. It helps simplify asynchronous programming in JavaScript and leads to cleaner, more manageable code.