How to use Async and Await with Array.prototype.map()

Using async/await combined with map() can be a little tricky. Find out how.

You want to execute an async function inside a map() call, to perform an operation on every element of the array, and get the results back.

How can you do so?

This is the correct syntax:

const list = [1, 2, 3, 4, 5] //...an array filled with values

const functionThatReturnsAPromise = item => { //a function that returns a promise
  return Promise.resolve('ok')
}

const doSomethingAsync = async item => {
  return functionThatReturnsAPromise(item)
}

const getData = async () => {
  return Promise.all(list.map(item => doSomethingAsync(item)))
}

getData().then(data => {
  console.log(data)
})

The main thing to notice is the use of Promise.all(), which resolves when all its promises are resolved.

list.map() returns a list of promises, so in result we’ll get the value when everything we ran is resolved.

Remember, we must wrap any code that calls await in an async function.

See the promises article for more on promises, and the async/await guide.

It can be difficult to visualize the example with those placeholder function names, so a simple example of how to use this technique is this Prisma data deletion function I wrote for a Twitter clone to first delete tweets and then users:

export const clearData = async (prisma) => {
  const users = await prisma.user.findMany({})
  const tweets = await prisma.tweet.findMany({})

  const deleteUser = async (user) => {
    return await prisma.user.delete({
      where: { id: user.id }
    })
  }
  const deleteTweet = async (tweet) => {
    return await prisma.tweet.delete({
      where: { id: tweet.id }
    })
  }

  const deleteTweets = async () => {
    return Promise.all(tweets.map((tweet) => deleteTweet(tweet)))
  }

  const deleteUsers = async () => {
    return Promise.all(users.map((user) => deleteUser(user)))
  }

  deleteTweets().then(() => {
    deleteUsers()
  })
}

Technically this could be much easier summarized as

export const clearData = async (prisma) => {
  await prisma.tweet.deleteMany({})
  await prisma.user.deleteMany({})
}

but the above code is also valid, and shows how to use promises in Array.map(), which is the point of this tutorial.

Download my free JavaScript Beginner's Handbook and check out my JavaScript Masterclass!

⭐️ Join the waiting list for the JavaScript Masterclass ⭐️