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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *