How to use promise. All()

Time:2021-7-27

How to use promise. All()

What is promise

Promise is an object that represents the final completion or failure of an asynchronous operation and its result value. Simply put, promise is a placeholder for a value that will be generated at some point in the future.
Promise is a very useful object for handling asynchronous operations.
JavaScript provides a help functionPromise.all(promisesArrayOrIterable)Support parallel processing of multiple promises, and obtain the result value in an aggregate array. Let’s learn how promise. All () works.

1.Promise.all()

Promise. All() is a built-in help function that can accept promise array. The format returned by the function is as follows:

const allPromise = Promise.all([promise1, promise2, ...]);

You can then extract the value returned by promise using the then able syntax:

`allPromise.then(values => {
values; // [valueOfPromise1, valueOfPromise2, …]
}).catch(error => {
error; // rejectReason of any first rejected promise
});`

Or use async / await syntax:
`try {
const values = await allPromise;
values; // [valueOfPromise1, valueOfPromise2, …]
} catch (error) {
error; // rejectReason of any first rejected promise
}`

The most useful is that promise can get resolved or rejected through promise. All()

If all promise object requests succeed, allpromise is an array of promises. The return order of promises is related to the order in which the array is stacked.

How to use promise. All()

However, if the last project is rejected, allpromise will also enter the reject state and will not wait for other projects to be returned correctly.

How to use promise. All()

Example of simultaneous asynchronous operations

To demonstrate the workflow of promise. All (), we choose to use two help classes, resolvetimeout (value, delay) and rejecttimeout (reason, delay)
`function resolveTimeout(value, delay) {
return new Promise(

resolve => setTimeout(() => resolve(value), delay)

);
}

function rejectTimeout(reason, delay) {
return new Promise(

(r, reject) => setTimeout(() => reject(reason), delay)

);
}`

Resolvetimeout (value, delay) returns a promise object and carries a parameter value
Another reason for rejecting the timeout object is also carried.

As in the simulation example, the store provides a list of vegetables and fruits at the same time, and each list is accessed through asynchronous operation:
`const allPromise = Promise.all([
resolveTimeout([‘potatoes’, ‘tomatoes’], 1000),
resolveTimeout([‘oranges’, ‘apples’], 1000)
]);

// wait…
const lists = await allPromise;

// after 1 second
console.log(lists);
// [[‘potatoes’, ‘tomatoes’], [‘oranges’, ‘apples’]]`

Const allpromise = promise.all ([…]) returns the promise object of the new allpromise.
Const lists = await allpromise statement declares to wait 1 second until all promise objects are pressed into the allpromise array.
Finally, the output results in the list are: [‘potatoes’,’tomatoes’], [‘oranges’,’apples’]]

The order of promises array directly affects the order of results.

The promises of vegetables are the first item, while the promises of fruits are the second item in the input array. The result array contains values in the same order — the first list of vegetables and the second list of fruits.

3. Example: when a promise is blocked

Now imagine this: there is no fruit in the grocery store. In this case, let’s use an error prompt to return reject: new error (‘out of fruits! ‘):
`const allPromise = Promise.all([
resolveTimeout([‘potatoes’, ‘tomatoes’], 1000),
rejectTimeout(new Error(‘Out of fruits!’), 1000)
]);

try {
// wait…
const lists = await allPromise;
} catch (error) {
// after 1 second
console.log(error.message); // ‘Out of fruits!’
}`

In this case, allpromise = promise. All ([…]) returns a promise. However, when promise (fruits) returns an error, new error (‘out of fruits! ‘) All allpromise objects will also return the reject method with the same error.
Promise. All() does not take effect even though promise for vegetables has been implemented. The behavior of promise.all ([…]) is fail fast. If there is a promise reject in the queue, other promises are also rejected and return the same reason.

4. Summary

Promise. All ([…]) is a useful helper function that allows you to perform asynchronous operations in parallel using the fault fast strategy and aggregate the results into an array.

Original address:https://dmitripavlutin.com/pr…