What is Promise.allSettled()! Novice and veteran?

Keywords: ECMAScript Promise

What is Promise.allSettled()! Novice and veteran?

Promise.allSettled()   Method returns a statement that has been returned in all given promises   fulfilled   or   rejected   Posterior   Promise, with an array of objects, and each object represents the corresponding promise result.

Next, let's take a look   Promise.allSettled()   How it works.

1. Promise.allSettled()

Promise.allSettled()   It can be used to perform independent asynchronous operations in parallel and collect the results of these operations.

This function accepts a   promise   Array (usually an iteratable object) as a parameter:

const statusesPromise = Promise.allSettled(promises);

When all inputs   promises   All by   fulfilled   or   rejected   When, statusesPromise   Will resolve to an array with their states

  1. { status: 'fulfilled', value: value }  — If the corresponding promise has   fulfilled

  2. perhaps   {status: 'rejected', reason: reason}   If the corresponding promise has been   rejected

After resolving all promises, you can use   then   Syntax to extract their status:

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

Or use   async/await   Syntax:

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

2. Take fruits and vegetables

In-depth study   Promise.allSettle()   Before that, let's define two simple   helper   Function.

First, resolveTimeout(value, delay) returns a promise after   delay   Use after time   value   To achieve

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

Second, reject timeout (reason, delay)  - Returns a promise after   delay   Reject reason after time.

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

2.1 All promises fulfilled

We also visited vegetables and fruits at the local grocery store. 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'] }
// ]

Online case: codesandbox.io/s/all-resol...

Promise.allSettled([...]) returns a promise   Statusspromise, which is solved in 1 second. After the vegetables and fruits are solved, it is solved in parallel.

statusesPromise   Resolves to an array containing states.

  1. The first item of the array contains the completed status of the vegetables: status: 'completed', value: ['potatoes',' tomato ']}
  2. In the same way, the second item is the completion status of the fruit:   { status: 'fulfilled', value: ['oranges', 'apples'] }

2.2 a promise is rejected

Imagine that there is no fruit in the grocery store. In this case, we reject the promise of fruit.

promise.allsettle()   How does it work in this situation?

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

Online case: codesandbox.io/s/one-rejec...

Promise.allSettled([...])   The returned promise is in   one   Parses into a status array in seconds:

  1. The first item in the array, vegetables   promise   Successfully resolved: {status: 'fully', value: ['potatoes',' Tomatoes']}

  2. The second item is a rejected status because the fruit promise is rejected:   { status: 'rejected', reason: Error('Out of fruits') }

Even if the second promise in the input array is rejected, statusesPromise will successfully parse a status array.

2.3 all projects are rejected

What if the grocery store sells out of vegetables and fruits? In this case, both promise s will be 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!') }
// ]

Online case: codesandbox.io/s/all-rejec...

In this case, statusesPromise still successfully resolves to an array of states. However, the array contains the status of the rejected promise.

3. Summary

Promise.allSettled(promises) can run promise in parallel and collect the status (fully or reject) into an aggregate array.

Promise.allSettled(...) is very effective when you need to perform parallel and independent asynchronous operations and collect all results, even if some asynchronous operations may fail.

~~After that, I'm the dish washing wisdom. Your praise and watching are the greatest recognition for me.

The possible bugs in editing cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful bug monitoring tool   Fundebug

Posted by bobc on Fri, 08 Oct 2021 19:45:57 -0700