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

> Learn how to run an async function inside Array.prototype.map() and wait for every result by wrapping the returned promises in Promise.all() the right way.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2018-10-11 | Updated: 2021-07-08 | Topics: [JavaScript](https://flaviocopes.com/tags/js/) | Canonical: https://flaviocopes.com/javascript-async-await-array-map/

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:

```js
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](https://flaviocopes.com/javascript-promises/) for more on promises, and the [async/await guide](https://flaviocopes.com/javascript-async-await/).

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](https://flaviocopes.com/prisma/) data deletion function I wrote for a Twitter clone to first delete tweets and then users:

```js
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 

```js
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.
