Technical section – how to use promise. All ()

Time:2021-9-15

How to use promise. All()

Hello, everyone, I’mFront end senior Joshua
Enthusiastic about open source and writing articles, the purpose is to help college students. Young partners who have just entered the workplace can build their own front-end learning system as soon as possible.
If you haveConfusion in learning, welcome to follow me,Communicate with me and I’ll reply to you in real time

Introduction to promise. All()

Promise.all(promisesArrayOrIterable)Is an auxiliary function in JavaScript. It can help us process multiple promises in parallel at one time, and then aggregate the results into an array. This is the aggregation result, not the return result.

It actually returns a promise object.

Parameters: promise array

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

Then you can pass.thenTo getPromise.all(promisesArrayOrIterable)Aggregate results after processing

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

Or useasync / awaitSyntax:

try {
  const values = await allPromise;
  values; // [valueOfPromise1, valueOfPromise2, ...]
} catch (error) {
  error;  // rejectReason of any first rejected promise
}s

The most interesting point about promise. All () is the way promise is resolved / rejected in parameters.

  1. If all promises are successfully resolved, promise. All() aggregates the completed values of each promise into an array. We can obtain their corresponding completion values according to the order of each promise in the original parameters.
    Technical section - how to use promise. All ()
  2. If one of the promises is rejected, promise. All() will reject it immediately for the same reason (without waiting for other promises to resolve).
    Technical section - how to use promise. All ()

Therefore, for the characteristics of promise. All(), just remember three words:

  1. parallel
  2. Aggregation results
  3. Rapid failure

The following examples are all around these three core words.

Before entering the example, let’s write two auxiliary functions:
Resolvetimeout (value, delay): returns a promise object. The promise object will delay for a period of time and trigger resolve
Rejecttimeout (reason, delay): returns a promise object. This promise object will delay for a period of time and trigger reject

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)
  );
}

All promises are reslove

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

From the code, we can know:

  1. The order of the promises array is the order of the aggregate results.
  2. All promises are resolved. After resolve, the results of each promsie will be aggregated into the array

A promise was rejected

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!'
}

From the code, we can know:

  1. As long as a promise is rejected, promise.all will immediately reject and return the same error.
    This is rapid failure.

Simulation source code implementation

async function myPromiseAll (arr) {
  const resultArr = [];
  for (let i = 0; i < arr.length; i ++) {
    try {
      const data = await arr[i];
      resultArr.push(data); //  Promise is realolve and pushed into resultarr
    } catch (e) {
      throw e; //  As long as one is rejected (that is, a trigger error), an error is thrown immediately
    }
  }
  return resultArr;
}

Summary:

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

Move your hands

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