/

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

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

When using async/await in conjunction with the map() function, it can be a bit tricky. In this article, we will explore how to achieve this effectively.

If you want to execute an async function inside a map() call to perform an operation on every element of an array and retrieve the results, here’s how you can do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 key here is to use Promise.all(), which resolves when all the promises it receives are resolved. Since list.map() returns a list of promises, we are able to obtain the resolved values in the “data” variable.

Remember to wrap any code that calls await in an async function.

For more information on promises, you can refer to the promises article. Additionally, you can check out the async/await guide for further insights.

To provide a clearer understanding, let’s take a look at a practical example. Here’s a sample data deletion function written for a Twitter clone using Prisma:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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()
})
}

Although the functionality can be achieved in a simpler way as shown above, the previous code example demonstrates how to use promises in Array.map(). This tutorial aims to focus on that aspect.

Tags: async/await, Array.map(), promises, Prisma