Perform multiple independent asynchronous operations in parallel – promise. Allsettled()

Time:2021-9-17

Perform multiple independent asynchronous operations in parallel – promise. Allsettled()

<!– TOC –>

<!– /TOC –>

introduce

Promise.allsettled (promises) is an auxiliary function. It runs promise in parallel, stores the changed status (completed or rejected) in an array, and returns it to the developer for use.

When you have multiple asynchronous tasks that do not depend on each other (or are independent of each other), and you want to know the execution result of each promise task (whether completed or rejected), you usually use it.

Let’s see how promise. Allsettled() is used.

How to use promise. Allsettled()

1.Promise.allSettled()

Promise. Allsettled() can be used forparallelimplementindependentofasynchronousAnd collect the results of these asynchronous operations.

This function takes a promise array (or usually an iteratable array) as an argument:

const statusesPromise = Promise.allSettled(promises);

When we pass in parametersPromises arrayAfter the status of each item has changed (whether completed or rejected),Promise.allSettledWillPromises arrayThe execution results of each item in the are stored in an array and returned to the developer for use.

Returned arraystatusesPromiseThe format of each item in is as follows:

  1. { status: 'fulfilled', value: value }– if the corresponding promise has been completed
    perhaps
  2. { status: 'rejected', reason: reason }– if the corresponding promise has been rejected

After all the promises have been resolved or rejected, you can use. Then to perform subsequent operations on them:

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

Or follow them up with async / await:

const statuses = await statusesPromise;

statuses; // [{ status: '...', value: '...' }, ...]

2. Example: simply use promise. Allsettled()

Before understanding promise. Allset(), let’s define two simple auxiliary functions:

First, resolvetimeout (value, delay) — returns a promise, which will trigger the resolve function after a period of time:

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

Secondly, rejecttimeout (reason, delay) — returns a promise, which will trigger the reject function after a period of time:

function rejectTimeout(reason, delay) {
  return new Promise(
    (r, reject) => setTimeout(() => reject(reason), delay)
  );
}

Let’s use these two auxiliary functions to test the function of promise. Allsettled().

2.1. All promises have been completed

Next, I will perform some asynchronous operations at the same time:

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

Promise.allsettled ([…]) returns an array of statusspromise, and both asynchronous operations are executed in parallel.
statusesPromiseyesPromise.allSettled([...])An array returned. Each item in the array contains the status after the corresponding asynchronous operation is completed:

  1. arraystatusesPromiseThe first item of the contains the completion status: {status: ‘completed’, value: [‘potatoes’,’ Tomatoes’]}
    Again,
  2. arraystatusesPromiseThe second item of contains the completion status: {status: ‘completed’, value: [‘Oranges’,’ Apples’]}.

2.2 a promise has been rejected

If one of multiple parallel independent asynchronous operations is rejected, thenPromise.allSettled([...])What will you do?

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

Let me look at the results and we will soon understand:

  1. The first item is promised because the resolve function is triggered. The first item of the array is {status: ‘fully’, value: [‘potatoes’,’ Tomatoes’]}
  2. Because the second item triggers the reject function and promise is rejected, the second item status of the array is modified to rejected status: {status: ‘rejected’, reason: error (‘out of fruits’)}.

Even if an item changes to the rejected state, but in the endPromise.allSettledThe function will contain this item and store it in the return value.

2.3 all promises have been rejected

Let’s look at the following code:

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

under these circumstances,Promise.allSettledAn array is still returned. However, the state of each item in the array is the rejected state.

Summary:

Promise.allSettled(promises)Allow youparallelimplementmutually independentAnd the status (completed or rejected) after the execution of each promise is stored in the array.

Promise. Allsettled (…) is useful when you need to perform parallel and independent asynchronous operations and get all the results of asynchronous operations, even if some asynchronous operations may fail.

compatibility:

reference resources:compatibilityvery good

reference resources

Move your hands

  • Welcome to my GitHub:@huangyangquang ⭐⭐
  • Welcome to my official account: front-line student Joshua
    <img width=”50%”>

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]