SEAN Z | Dev

a space for creativity and engineering

Promise.all for map iterator

Senario

When working on the backend api like aws lambda with node.js, there was an endpoint with a put call to update several tables in a sequencial manner. Such as followinig

const queryArray = [
    "update user_table set timezone = 'new_york'",
    "update membership_table set role = 'mafia boss' ",
    "update club_table set club_name = 'Red Espress'",
    ]

I initially used the map function to loop thru the query array and make database call in interation. If you want to use async/await inside the map function, you need to make sure each promise takes place inside of the try/catch block so that the error will be returned.

const results = queryArray.map(async (query) => {
    try {
        const res = await client.query(query)
        return res
    } catch (err) {
        return err
    }
})

Because I use the async/await and I thought the query should be executing synchroneous manner but what i end up gettinig was followiing

console.log(results)
[Promise<Pending>, Promise<Pending>, Promise<Pending>]

Async/Await For Map

The reason I was getting the array of pending promises was because none of promises didn't resolve inside the map iterator. the proper way to resolve them all is to

const results = await Promise.all(queryArray.map(async (query) => {
    try {
        const res = await client.query(query)
        return res
    } catch (err) {
        return err
    }
}))

Reason

the map iterator excutes in synchroneous manner thus it doesn't make the wait for the promise to be over, instead it returns a promise pending object.

Copyright © 2019 Sean Zhang

Handcrafted in Washington, DC