Search code examples
javascriptasync-awaites6-promise

Promise.all() not successful when pushing async promises


I have these two snippets of code:

A (https://repl.it/repls/HarmlessSupportiveUpgrades)

array = []
const promise = async (i) => console.log(i)
for (const num of [1, 2, 3, 4, 5]) {
    array.push(promise(num))
}

Promise.all(array)

B(https://repl.it/repls/ColdHealthyAssignment)

array = []
for (const num of [1, 2, 3, 4, 5]) {
    array.push(async (i) => console.log(i))
}

Promise.all(array)

I'm confused as to why the A will successfully print to the console, but B won't. How come?


Solution

  • On the first snippet you are calling the function with num as parameter.

    But on the second you are pushing function declarations to the array

    if you replace

    array.push(async (i) => console.log(i))
    

    on the second snippet with

    array.push((async (i) => console.log(i))(num))
    

    it will work the same way as the first snippet.