Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Promise.allSettled () in javascript

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use Promise.allSettled () in javascript, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand.

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

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

1. Promise.allSettled ()

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

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

Const statusesPromise = Promise.allSettled (promises)

When all input promises is fulfilled or rejected, statusesPromise is parsed into an array with their states

{status: 'fulfilled', value: value}-if the corresponding promise is already fulfilled

Or {status: 'rejected', reason: reason} if the corresponding promise has been rejected

After parsing all promises, you can use then syntax to extract their state:

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

Or use the async/await syntax:

Const statuses = await statusesPromise;statuses; / / [{status: '...', value: '...'}, 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, which is implemented with value after the delay time has elapsed

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

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

Finally, we use these helper functions to experiment with 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 secondconsole.log (statuses); / / [/ {status:' fulfilled', value: ['potatoes',' tomatoes']}, / / {status: 'fulfilled', value: [' oranges', 'apples']} / /]

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

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

The statusesPromise parses to an array containing states.

The first item of the array contains the completed status of vegetables: status: 'fulfilled', value: [' potatoes', 'tomatoes']}

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 fruit's promise.

How does promise.allsettle () 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 secondconsole.log (statuses); / / [/ {status: 'fulfilled', value: [' potatoes', 'tomatoes']}, / / {status:' rejected', reason: Error ('Out of fruits')} / /]

Online case: https://codesandbox.io/s/one-rejected-ij3uo?file=/src/index.js

Promise.allSettled ([...]) The returned promise is parsed into a status array after 1 second:

The first item of the array, vegetable promise successfully parses: {status: 'fulfilled', value: [' potatoes', 'tomatoes']}

Second, because the fruit promise is rejected, it is a rejection status: {status: 'rejected', reason: Error (' Out of fruits')}

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

2.3All promises are rejected

What if all the vegetables and fruits in the grocery store are sold out? In this case, both promise will be rejected.

Const statusesPromise = Promise.allSettled ([rejectTimeout (new Error ('Out of fruits), 1000), rejectTimeout (new Error (' Out of fruits'), 1000)]); / / wait...const statuses = await statusesPromise;// after 1 secondconsole.log (statuses); / [/ {status: 'rejected', reason: Error (' Out of fruits')}, / / {status: 'rejected', reason: Error (' Out of fruits')} / /]

Online case: https://codesandbox.io/s/all-rejected-z4jee?file=/src/index.js

In this case, the statusesPromise is still successfully parsed into an array of states. However, the array contains the status of the rejected promise.

Thank you for reading this article carefully. I hope the article "how to use Promise.allSettled () in javascript" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report