This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Dmitri Pavlutin translated by Dmitri Pavlutin

Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom.

In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.

The promise.allSettled () method returns a Promise after all the given promises have fulfilled or rejected, with an array of objects each representing the corresponding Promise result.

Next, let’s see how Promise.AllSettled () works.

1. Promise.allSettled()

Promise.allsettled () can be used to perform separate asynchronous operations in parallel and collect the results of those operations.

This function takes an array of Promises (usually an iterable) as an argument:

const statusesPromise = Promise.allSettled(promises);
Copy the code

When all the input promises are fulfilled or Rejected, the statusesPromise will be resolved into an array with their states

  1. {status: ‘depressing ‘, value: value} — if the corresponding promise has been fulfilled

  2. Or {status: ‘rejected’, reason: Reason} if the corresponding promise has already been rejected

After parsing all Promises, you can use the then syntax to extract the state of promises:

statusesPromise.then(statuses => {
 statuses; // [{ status: '...', value: '...' }, ...]
});
Copy the code

Or use async/await syntax:

const statuses = await statusesPromise;
statuses; // [{ status: '...', value: '...' }, ...]
Copy the code

2. Pick up fruits and vegetables

Before delving into promise.allsettle (), let’s define two simple helper functions.

First, resolveTimeout(value, delay) returns a promise implemented with value after the delay

function resolveTimeout(value, delay) {
  return new Promise(
    resolve => setTimeout(() => resolve(value), delay)
  );
}
Copy the code

Second, rejectTimeout(Reason, delay) – Return a promise to reject Reason after the delay.

Finally, we use these helper functions to experiment with promise.allsettle().

2.1 All promises fulfilled

We also visit local grocery stores for vegetables and fruits. Accessing each list is an asynchronous 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'] }
// ]
Copy the code

IO /s/all-resol…

Promise.allSettled([…] Returns a Promise statusesPromise that is resolved in 1 second, just after the vegetables and fruits have been resolved, in parallel.

The statusesPromise resolves to an array of states.

  1. The first item in the array contains the completed state of the vegetable:status: 'fulfilled', value: ['potatoes', 'tomatoes'] }
  2. In the same way, the second item is the finished state of the fruit:{ status: 'fulfilled', value: ['oranges', 'apples'] }

2.2 A Promise is rejected

Imagine there’s no fruit left in the grocery store. In this case, we reject the promise of fruit.

How does promise.allsettle() work in this 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!') }
// ]
Copy the code

Codesandbox.io /s/one-rejec…

Promise.allSettled([…] ) returns a promise that parses into a state array after 1 second:

  1. {status: ‘big pity ‘, value: [‘potatoes’, ‘tomatoes’]}

  2. {status: ‘rejected’, reason: Error(‘Out of fruits’)} {status: ‘rejected’, reason: Error(‘Out of fruits’)}

Even if the second promise in the input array is rejected, the statusesPromise still successfully parses a state array.

2.3 All promises are rejected

What if the grocery store runs out of vegetables and fruit? In this case, both promises are rejected.

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!') } // ]Copy the code

Codesandbox.io /s/all-rejec…

In this case, the statusesPromise still resolves successfully into a state array. However, this array contains the state of the rejected promise.

3. Summary

Promise. AllSettled (Promises) Can run promises in parallel and collect states (depressing or Reject) into an aggregate array.

Promise.allSettled(…) This is useful when you need to perform parallel and separate asynchronous operations and collect all the results, even if some of the asynchronous operations may fail.

~~ finish, I am a bowl smart, your thumbs up and look is the biggest recognition of my bowl.

The possible bugs in editing can not be known in real time. In order to solve these bugs after the event, I spent a lot of time on log debugging. By the way, I recommend a good bug monitoring tool for youFundebug.


Original text: dmitripavlutin.com/promise-all…

communication

This article is updated weekly, you can search wechat ** [big move the world] the first time to read, reply [welfare] ** there are many front-end video waiting for you, this article GitHub github.com/qq449245884… Already included, welcome Star.