2

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 results.push(...tmp) } 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?

1
  • You use it instead of a for loop. Create an array of {page: i} objects, .map() them to the callMyApi() promise, then pass the resulting array to Promise.all and await the result. Commented Jul 16, 2021 at 7:58

2 Answers 2

3

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

What happens when one of promise call fails ? This code will blow up. You should also surrond with catch block here
1

Example below:

async function myWork() { let results = []; let param; for (i = 1; i < 11; i++) { param = { page: i }; results.push(callMyApi(param)); } const res = await Promise.all(results); return res.flat(); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.