DEV Community

Jamie Halvorson
Jamie Halvorson

Posted on

How do I use Async/Await with Array.map?

Await

You can't, but you can do something similar. This always trips me up so I thought I'd better write it down.

You can't async/await Array.map since synchronous code won't sit and wait for your asynchronous code to resolve, instead it will the fire the function and move on. This is desired behaviour as we don't want our Array.map to block the thread otherwise nothing would run whilst Array.map goes and does its thing. Knowing that is cool, however, it doesn't really help us if we need to await our Array.map().

Thankfully there is a solution, we can achieve what we want by utilising Promise.all

For example, the following won't work:

const postIds = ['123', 'dn28e29', 'dn22je3'];

const posts = await postIds.map(id => {
  return axios
    .get(`https://example.com/post/${id}`)
    .then(res => res.data)
    .catch(e => console.error(e));
}

console.log(posts) // [] it returns the promise, not the results 💩
Enter fullscreen mode Exit fullscreen mode

But this will:

const postIds = ['123', 'dn28e29', 'dn22je3'];

const posts = posts.map(post => {
  return axios
    .get(`https://example.com/post/${post.id}`)
    .then(res => res.data)
    .catch(e => console.error(e));
}

Promise.all(posts).then(res => console.log(`We have posts: ${res}!`));
Enter fullscreen mode Exit fullscreen mode

Instead of immediately returning the Array.map we're assigning it to a variable and passing that variable to Promise.all, once that resolves we then have access to the new array returned by Array.map.

Happy JavaScripting.

Top comments (1)

Collapse
 
saumyanayak profile image
Saumya Nayak

Thanks for this ! It helped