How to call an asynchronous function within a map with JavaScript?

Estimated read time 2 min read

You can call an asynchronous function within a map function in JavaScript by returning a Promise from the map function and using the await keyword inside the callback function. Here’s an example:

async function fetchUserData(userIds) {
  const promises = userIds.map(async (userId) => {
    const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
    const user = await response.json();
    return user;
  });
  const userData = await Promise.all(promises);
  return userData;
}

fetchUserData([1, 2, 3])
  .then((userData) => {
    console.log(userData);
  })
  .catch((error) => {
    console.error(error);
  });

In this example, we define an async function fetchUserData that takes an array of user IDs as an argument. We use the map function to create an array of Promise objects that call an asynchronous function that fetches user data from a web API using the fetch function. Inside the map callback function, we use the await keyword to wait for the response to resolve and parse the JSON data.

We then use Promise.all to wait for all the promises to resolve, and return an array of user data. Finally, we call fetchUserData with an array of user IDs, and use the then method to log the user data to the console. We also use the catch method to handle any errors that might occur.

Note that you can also use the for...of loop to iterate over an array and call an asynchronous function using the await keyword. The main difference between map and for...of is that map returns a new array, while for...of does not. If you don’t need to return a new array, for...of can be a simpler option.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply