Why does passing in an array of async functions to Promise.all work as expected?

Advertisements
await Promise.all(
  arr_tar.map(async (tar) => {
    return {
      n: await tar_get_one(tar),
      name: tar.name,
    };
  })
)

Why is the code above. There elements of the input array are async functions, but they are not invoked by anything.

>Solution :

According to MDN:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

In the code shown, Array#map will call the async callback function on each element of the array and since async functions return Promises the result will be an array of Promises. Promise.all takes an iterable of Promises as input so this works.

Leave a ReplyCancel reply