Promise.all with for loop in node.js

I collect the information of each page from 1 to 10 as API in node.js.

Now I use this code.

async function myWork() {
  let results = []
  let tmp
  let param
  for (i=1; i<11; i++) {
    param = {'page': i}
    tmp = await callMyApi(param) // return a list
  return results

In this case, each callMyApi behaves like sync.

But I don’t care about page order.

So, to speed it up, I want to use something like promise.all to process it in parallel.

How can I use promise.all in for loop in this case?


You can use Promise.all() with concat().

async function myWork() {
  let results = [];
  let promises = [];
  let param;
  for (i=1; i<11; i++) {
    let param = {'page': i}
    let tmpPromise = callMyApi(param);
    promises .push(tmpPromise);
  //promises is now an array of promises, and can be used as a param in Promise.all()
  let resolved = await Promise.all(promises);
  //resolved is an array of resolved promises, each with value returned by async call
let indivResult = resolved.forEach(a => 
  results = results.concat(a));
 //for each item in resolved array, push them into the final results using foreach, you can use different looping constructs here but forEach works too
  return results;