I want to make map run asynchronously. I tried using async and Promise.all but I not sure where I am going wrong. This is code I have written
// this is the id => [1,2,3] and total of each => [2, 3, 2]
useEffect(()=> {
countNumFunc(idList)
})
const countNumFunc = (idlist) => {
let count = 0
Promise.all(idList.map(async (id) => {
console.log("id = ", id)
getInfoFromDb(id).then((res) => {
if(res.data) {
count = count + res.data.total
console.log("Count = ", res.data.total)
}
}).catch(error => {
console.log("error = ", error)
})
}))
console.log("Count total = ", count)
}
Here the output should have been:
id = 1
Count = 2
id = 2
Count = 5
id = 3
Count = 7
Count total = 7
But the output is:
id = 1
id = 2
id = 3
Count total = 0
Count = 2
Count = 3
Count = 2