What is Promise.allSettled()! Novices and veterans have to know?

前端小智
中文
Author: Dmitri Pavlutin
Translator: Frontend Xiaozhi
Source: dmitripavluti

If you have dreams and dry goods, search for [Moving to the World] Follow the brushing wisdom who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

Promise.allSettled() method returns a promise all have been given in fulfilled or rejected after promise , and having an array of objects, each object corresponding to the result showing promise.

Next, let's take a look at how Promise.allSettled() works.

1. Promise.allSettled()

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

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

const statusesPromise = Promise.allSettled(promises);

When all inputs promises are fulfilled or rejected , statusesPromise will be parsed into an array with their status

  1. { status: 'fulfilled', value: value } — If the corresponding promise is already fulfilled
  2. Or {status: 'rejected', reason: reason} if the corresponding promise is already rejected

image.png

After parsing all promises, you can use the 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

Before delving into Promise.allSettle() , let's define two simple functions helper

First, resolveTimeout(value, delay) returns a promise, the promise elapsed delay after time with value achieved

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

Second, rejectTimeout(reason, delay) - returns a promise, the elapsed delay time after rejection reason .

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

2.1 All promises fulfilled

We also visited the local grocery store 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'] }
// ]

Online example: https://codesandbox.io/s/all-resolved-yyc0l?file=/src/index.js

Promise.allSettled([...]) returns a promise statusesPromise , which is resolved within 1 second, and is resolved in parallel just after the vegetables and fruits are resolved.

statusesPromise parsed as an array containing states.

  1. The first item of the array contains the completed status of the vegetable: status: 'fulfilled', value: ['potatoes', 'tomatoes'] }
  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 more fruit in the grocery store. In this case, we reject the promise of fruit.

promise.allsettle() 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 example: https://codesandbox.io/s/one-rejected-ij3uo?file=/src/index.js

Promise.allSettled([...]) returned promise in 1 after resolved to a second state array:

  1. The first item of the array, vegetable promise successfully parsed: { status: 'fulfilled', value: ['potatoes', 'tomatoes'] }
  2. The second item, because the fruit promise was rejected, is a rejection status: { status: 'rejected', reason: Error('Out of fruits') }

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

2.3 All promises are rejected

What if the vegetables and fruits in the grocery store are all sold out? In this case, both promises 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 example: https://codesandbox.io/s/all-rejected-z4jee?file=/src/index.js

In this case, statusesPromise is still successfully parsed as a state array. However, the array contains the status of rejected promises.

3. Summary

Promise.allSettled(promises) parallel and collect the status (fulfilled or rejected) into an aggregate array.

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

~~ At the end, I am the wisdom of the bowl, your likes and watching is the biggest recognition of my bowling.

possible bugs in 1616cc0123bfde editing cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .


Original: https://dmitripavlutin.com/promise-all-settled/

comminicate

The article is continuously updated every week, you can search for [Great Move to the World] Read it for the first time, reply [Benefit] are many front-end videos waiting for you, this article GitHub https://github.com/qq449245884/xiaozhi has been included, welcome to Star.

阅读 657

终身学习者
我要先坚持分享20年,大家来一起见证吧。
62.9k 声望
95k 粉丝
0 条评论
62.9k 声望
95k 粉丝
文章目录
宣传栏