0

I care just about performance. So just need to run nested promises in for loop. I do not care if one of promise fails.. So just want to execute it as quickly as possible. Not sure if I can do Promise.all. What if it's for loop for 1000 promises that return large data in fetch response? And will such architecture cause response data issue that will interfere with other promise responses?

let data = [//very large array ...]

for (let index = 0; index < data.length; index++) {
    Promise1(data[i]).then(result => {
        if (result) {
            Promise2(result.data).then(result => {
                if (resullt) {
                    // STORE DATA IN DB
                }
            }).catch(err => {
                // do nothing
            })
        }
    }).catch(err => {
        // do nothing
    })
}
John Glabb
  • 1,336
  • 5
  • 22
  • 52
  • possibly see: [Execute batch of promises in series. Once Promise.all is done go to the next batch](https://stackoverflow.com/questions/37213316/execute-batch-of-promises-in-series-once-promise-all-is-done-go-to-the-next-bat) or [How to use promise.all with a specified number of parallel processing at Node.js](https://stackoverflow.com/questions/70469239/how-to-use-promise-all-with-a-specified-number-of-parallel-processing-at-node-js) – pilchard Nov 08 '22 at 21:23
  • do not you see any issues with the code above? – John Glabb Nov 08 '22 at 21:28
  • This will execute pretty much as fast as possible, running the entire loop of asynchronous operations in parallel. What is will not do is let you control how many asynchronous operations are "in flight" at the same time or let you know when everything is done. There are much better solutions for both of those. But, you didn't say either of those are requirements. – jfriend00 Nov 08 '22 at 23:11
  • See [mapConcurrent()](https://stackoverflow.com/questions/46654265/promise-all-consumes-all-my-ram/46654592#46654592) for the ability to control how many operations are running in parallel in flight at the same time. – jfriend00 Nov 08 '22 at 23:17
  • thank you jfriend00.. I think I'm good with running my code as was as it can.. – John Glabb Nov 08 '22 at 23:21
  • Note, if your array is very large, you may run into some problems (either with local resources or with the target host) when trying to run a zillion operations in parallel all at once. Whether or not this is a problem is situation-specific so we'd have to see the real code and the real asynchronous operations and the real array to advise more specifically. – jfriend00 Nov 08 '22 at 23:26
  • `Promise.all` will likely not meet your requirements because it will fail as soon as the first promise fails. `Promise.allSettled` would be a better fit. In order to complete this operation as fast as possible and in order to keep the main thread of execution free for the user interface, you might like to use worker threads. – Ben Aston Nov 09 '22 at 09:04

0 Answers0