How to use promise.any ()
The original link: dmitripavlutin.com/promise-any…
Some notes on translation:
Promise is a state machine with three states
- Pending on
- Perform this state after depressing resolve
- This state is entered after Rejected Reject
The state transition process is as follows:
It will be in the translationFulfilled
Finish, finish, finishRejected
Be rejected
Promise. Any (Promises) is a help function that executes multiple Promise requests in parallel and returns the Promise value of the first successful resolve.
Let’s see how promise.any () works
1. Promise.any()
Promise.any() is useful for performing independent asynchronous operations in a parallel and race manner, which can obtain the value of any Promise that is fulfilled first.
This function takes a list of promises (or iterables) as an argument
const anyPromise = Promise.any(promises);
Copy the code
When anyPromise in the promise list completes,anyPromise is immediately resolved to the value of that promise.
You can use the then syntax to get the value of the first promise
anyPromise.then(firstValue => { firstValue; // the first fullfilled promise value});Copy the code
Or use async/await:
const firstValue = await anyPromise; firstValue; // The value of the first fullfilled promiseCopy the code
This is a big pity. Any () returned Promise will be fulfilled with the first Promise which fulfills the request. Even the Promise which fails will be ignored.
If all promises fail or the entered promise array is empty, promise.any () is rejected and an aggregate error is thrown, containing error information for all promise requests.
- Take chestnuts -Fruits and vegetables
Before using promise.any (), let’s define two helper functions.
First, resolveTimeout(value, delay) — After delay milliseconds, return a fulfilled promise, which will pass the value parameter as the parameter of resolve.
function resolveTimeout(value, delay) {
return new Promise(
resolve => setTimeout(() => resolve(value), delay)
);
}
Copy the code
Second, rejectTimeout(Reason, delay) – Return a reject promise after the delay millisecond, with reason as an error message.
function rejectTimeout(reason, delay) {
return new Promise(
(r, reject) => setTimeout(() => reject(reason), delay)
);
}
Copy the code
Let’s test promise.any () using these helper functions.
2.1 All promises arefulfilled
Example: Get a list of purchases from a store:
const promise = Promise.any([
resolveTimeout(['potatoes', 'tomatoes'], 1000), resolveTimeout(['oranges', 'apples'], 2000)]);
// wait...
const list = await promise;
// after 1 second
console.log(list); // logs ['potatoes', 'tomatoes']
Copy the code
Try the demo.
Promise.any([…] (This promise will be fulfilled first, which is a big pity.)
The second promise completes after 2 seconds, but its value is ignored.
2.2 A Promise is rejected
Imagine a scenario where vegetables are not available at the store and vegetables’s promise is rejected. How does promise.any () return?
const promise = Promise.any([ rejectTimeout(new Error("Out of vegetables! "), 1000), resolveTimeout(["oranges", "apples"], 2000) ]); // wait... const list = await promise; // after 2 seconds console.log(list); // logs ['oranges', 'apples']Copy the code
Try the demo.
This is a tricky situation.
First, vegetables Promise was rejected after 1 second. But in this case, promise.any () skips the Promise and continues to wait for the result of the next Promise.
Finally, after 2 seconds, fruits promise completes and returns the corresponding value [‘oranges’, ‘apples’]. The return value is also promise.any ([…]) Resolve.
2.3 All Promises are Rejected
What happens if there are no vegetables or fruit in the store, a scenario in which both promises are rejected?
const promise = Promise.any([ rejectTimeout(new Error('Out of vegetables! '), 1000), rejectTimeout(new Error('Out of fruits!'), 2000)]); try { // wait... const list = await promise; } catch (aggregateError) { console.log(aggregateError); // logs AggregateError console.log(aggregateError.errors); // logs [Error('Out of vegetables!'), Error('Out of fruits!')] }Copy the code
Try the demo.
All entered promises are rejected, promise.any ([…]) The returned promise will also be rejected, and a special AggregateError will be thrown, which contains all the reasons why a promise was rejected.
Aggregate Error provides a special attribute errors: this is an array of rejected input promise errors.
- conclusion
Promise.any() can be useful for performing stand-alone asynchronous operations in parallel and race to get the value of the first Resolved Promise.
If all entered promises are rejected, promise.any ([…] ) returns a promise that is also rejected, and throws a special error, aggregateError, which provides an attribute, AggregateError. errors, which contains the reasons for all input promises to be rejected.
Note that promise.any ([]) is also rejected if the entered list is empty.
Challenge: What are the main differences between promise.any () and promise.race ()?