Categories
JavaScript Answers

How to call an asynchronous function within map with JavaScript?

Spread the love

Sometimes, we want to call an asynchronous function within map with JavaScript.

In this article, we’ll look at how to call an asynchronous function within map with JavaScript.

How to call an asynchronous function within map with JavaScript?

To call an asynchronous function within map with JavaScript, we can use the Promise.all method.

For instance, we write

const data = await Promise.all(
  data.map(async (item) => {
    try {
      item.fetchItem = await fetchFunc(item.fetchParams);

      return item;
    } catch (err) {
      throw err;
    }
  })
);

to call data.map with an async function as its callback.

The callback’s return statement returns the resolve value of the promise returned by the async function.

Then we call Promise.all on the returned array of promises to return a promise with an array of resolve value of each async function.

And then we use await to get the array of resolve values.

Conclusion

To call an asynchronous function within map with JavaScript, we can use the Promise.all method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.