0

I have a huge list of array of object, and I have an API endpoint that has queue limit, I got error writing this

arr.forEach(async o => {
  const result = await callAPI(o.id)

  //do something
})

but it is fine when I convert forEach to native for loop

for (let i = 0; i < arr.length; i++) {
    const o = arr[i];
    const result = await callAPI(o.id)

  //do something
};

Why? as I know I can do something similar with map where it is async, like

const transformedResult = Promise.all(arr.map(o => ({...o, newProp: await callApi(o.id) }) )
await transformedResult //will wait till callApi is resolved
Jennifer
  • 75
  • 5
  • 1
    The Promise resulting from the async callback in `forEach` goes unused - it's not connected with anything outside, and code below the `forEach` proceeds synchronously, without waiting. With `.map`, when the callback returns a Promise, the Promise *is* being used, so calling `Promise.all` on the result of the `.map` works – CertainPerformance Jan 09 '20 at 08:52
  • @CertainPerformance The promise.all solution is running exact the same with for loop? – Jennifer Jan 09 '20 at 09:01
  • When using `.map`, you need to make sure to return a Promise. Here, you're returning an object, not a Promise, so nothing is waited for – CertainPerformance Jan 09 '20 at 09:02
  • @CertainPerformance how does that look like? – Jennifer Jan 09 '20 at 09:03
  • Something like `o => callApi(o.id).then(newProp => ({ ...o, newProp }))` – CertainPerformance Jan 09 '20 at 09:04
  • hmm alright although the syntax look confusing – Jennifer Jan 09 '20 at 09:05
  • but hey read this article, the demo code is exactly like mine above https://dev.to/nyagarcia/array-map-async-await-2cif why for his case it is fine? – Jennifer Jan 09 '20 at 09:07
  • Your code is using a concise body to return an object; in that snippet, there's no concise body, rather, the callback is `async` (and so returns a Promise which resolves when all `await`s are done) and is a normal block – CertainPerformance Jan 09 '20 at 09:08
  • @CertainPerformance concise body means the {}? wow I didn't know that would make a huge difference – Jennifer Jan 09 '20 at 09:09
  • did you try to use rxjs ? promises is good but the main problem with promises when you need to execute multiple promises concurently you will notice alot of limitations and problems – youssef ali Jan 09 '20 at 09:28

0 Answers0