DEV Community

Jamie Halvorson
Jamie Halvorson

Posted on

8 3

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
saumyanayak profile image
Saumya Nayak

Thanks for this ! It helped

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay