Array.map() is a very useful function but unfortunately it only works with synchronous functions. A simple workaround to run async map functions is to use Promose.all() or its more tolerant brother Promise.allSettled():

 // Fails as soon as one of the map functions fails
const results = await Promise.all(array.map(asynMapFunction))

// Continues running even if one map function fails
const results = await Promise.allSettled(array.map(asynMapFunction))

This works because if the map function is an async, it’ll returns a promise. All we have to do is to wait till those promises from each individual invocation of map function is settled.

The main difference between the .all() and the relatively new .allSettled() is:

  • Promise.all() throws if the map function throws
  • Promise.allSettled() runs the map function for the whole array even if sometimes it throws

Therefore the output of the .allSettled() is an array of objects that tells whether the execution failed or not.

#javascript #nodejs #programming-tips

Async map with limited parallelism in Node.js
5.90 GEEK