📜  promise.all (1)

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

Promise.all

Introduction

JavaScript promises offer an easy way to handle asynchronous operations by providing a mechanism to handle return values asynchronously. Promise.all is a method that allows you to execute multiple promises in parallel and wait for all of them to be resolved before continuing.

Usage
Promise.all([promise1, promise2, promise3])
  .then(values => {
    console.log(values);
 });

The Promise.all() method takes an array of promises as input and returns a single promise that is resolved when all the promises in the input array are resolved. The output promise resolved with an array of values returned by each promise in the input array, in the same order.

Example
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 100, 3));

Promise.all([promise1, promise2, promise3])
  .then(values => {
    console.log(values); // [1, 2, 3]
  });

In the code above, promise1 and promise2 are resolved immediately and return values 1 and 2, respectively. promise3 is resolved after 100ms and returns value 3. Promise.all() waits for all the input promises to be resolved before executing the then method.

Error handling

If any of the input promises is rejected, Promise.all() rejects the output promise immediately and catch() method is called with the error.

const promise1 = Promise.resolve(1);
const promise2 = Promise.reject('error');
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 100, 3));

Promise.all([promise1, promise2, promise3])
  .then(values => {
    console.log(values);
  })
  .catch(error => {
    console.log(error); // error
  });
Conclusion

Promise.all() is a powerful method to handle multiple promises in parallel and wait for all of them to be resolved before continuing. It provides a simple and efficient way to handle multiple asynchronous operations and handle them in a single block of code.