2 ms·
To do parallel tasks in a loop for the situation I outlined (getting a final array of images from URIs), it would be really cumbersome, and your implementation
by mattdesl 3y ago
To do parallel tasks in a loop for the situation I outlined (getting a final array of images from URIs), it would be really cumbersome, and your implementation would be pretty much equivalent to the inner workings of Promise.all.
As others have mentioned; if you aren’t using Promise.all, you are likely missing a good deal of opportunities for easier and more performant async code.
- recursive 3y agoFor non-rejecting promises, `await Promise.all(promises)` is basically performance equivalent to `for (const p of promises) await p;`. In case you think the second one does serial work, here's a codepen for you. https://codepen.io/tomtheisen/pen/QWPOmjp https://codepen.io/tomtheisen/pen/QWPOmjp The "inner workings" could be a for loop, with the exception of rejected promises. The only opportunity for quicker resolution is when one of the promises reject, at which time Promise.all() immediately rejects. I think the allegations of "easier" are significantly overblown too.
- mattdesl 3y agoYou are right. I was mistakenly thinking that the alternative (naive approach) would be to write the promise-creating tasks within the for loop, but if they are not part of the loop, the functionality is basically equivalent to Promise.all. // A -- Async and parallel const results = await Promise.all(data.map((i) => delay(i))); // B -- Functionally equivalent to the above const promises = data.map((i) => delay(i)); const result = []; for (let a of promises) { const r = await a; result.push(r); } // C -- Problematic and naive approach: much slower const result = []; for (let i of data) { const r = await delay(i); result.push(r); }