Home > Blockchain >  Node JS: execution-time-wise, is generating array of promises and then using Promise.all better than
Node JS: execution-time-wise, is generating array of promises and then using Promise.all better than

Time:04-29

Suppose we have an array of objects that we have to upload to a cloud service, the service will do something with each object and the return a result. The service's client library has single function that uploads the object and waits for response. Which code will run faster:

async function extractDataInstantAwait(documents) {
  const results = [];
  for (const doc of documents) {
    results.push(await client.extractData(doc));
  }
  return results;
}
async function extractDataPromiseAll(documents) {
  const results = [];
  for (const doc of documents) {
    results.push(client.extractData(doc));
  }
  return Promise.all(results);
}

As far as I know, Nodejs does not run async code in multiple threads, so one may think that there is no difference between those. But, since every call to client.extractData may have to wait for response, the event loop of Nodejs should switch to next promise, do things there (upload another doc), and repeat. Perhaps, if service is slow at parsing each object, but we know it creates new threads for each operation, we can achieve some sort of concurent speed up?

Is my logic correct?

CodePudding user response:

Promise.all is faster, because Promise.all lets all the promises run in parallel, so your execution time will be the execution time of the longest promise (or close to it).

If you do it in a loop, the promises are executed one after the other, so your execution time will be the sum of all of the promises' execution times.

If you have to await three promises A, B and C which take respectively 200, 300 and 500 ms. With Promise.all they will run concurrently and you will have to wait for C for 500ms (A and B will have completed before that). With a loop you will have to wait 200ms for A, then wait 300ms for B, then wait 500ms for C, so you'll wait 1000ms in total.

  • Related