function returnPromise(item) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(item * item)
}, 1000)
})
}
async function main() {
const items = [1, 2, 3, 4]
const resultArr = []
items.map(async (item) => {
const result = await returnPromise(item)
console.log(result)
resultArr.push(result)
})}
console.log(resultArr)
i tested array map can work with async / await.
and i expect async/await works so that variable result results to square of item
and resultArr results to array of square of items.
But, stdout displays that
first, resultArr prints out empty array
and console.log in map prints out sequentially.
When i debug the code, control flow stops at await returnPromise(item), doesn't go down to console.log(result) and directly go to console.log(resultArr)
and after stack unwind and the Promise resolved, console.log(result) executed.
How can it happen?? it works like console.log(result) is callback, but they are in same code block.
I think console.log(result) should work when await returnPromise executed.
And I know i should have used Promise.all and didn't have to use async /await like above code but i just want to know why this situation happens...