map() function with async/await

The other answers have pretty well covered the details of how your examples behave, but I wanted to try to state it more succinctly.

const resultsPromises = myArray.map(async number => {
  return await getResult(number);
});
const resultsPromises = myArray.map(number => {
  return getResult(number);
});
  1. Array.prototype.map synchronously loops through an array and transforms each element to the return value of its callback.

  2. Both examples return a Promise.

    • async functions always return a Promise.

    • getResult returns a Promise.

    • Therefore, if there are no errors you can think of them both in pseudocode as:

const resultsPromises = myArray.map(/* map each element to a Promise */);
  1. As zero298 stated and alnitak demonstrated, this very quickly (synchronously) starts off each promise in order; however, since they’re run in parallel each promise will resolve/reject as they see fit and will likely not settle (fulfill or reject) in order.

  2. Either run the promises in parallel and collect the results with Promise.all or run them sequentially using a for * loop or Array.prototype.reduce.

Alternatively, you could use a third-party module for chainable asynchronous JavaScript methods I maintain to clean things up and–perhaps–make the code match your intuition of how an async map operation might work:

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

const getResult = async n => {
  await delay(Math.random() * 1000);
  console.log(n);
  return n;
};

(async () => {
  console.log('parallel:');
  await AsyncAF([1, 2, 3]).map(getResult).then(console.log);
  
  console.log('sequential:');
  await AsyncAF([1, 2, 3]).series.map(getResult).then(console.log)
})();
<script src="https://unpkg.com/[email protected]/index.js"></script>

Leave a Comment