0

I asked a question that was closed due to similar questions but even after reading those and seeing that map is not Promise aware, I have tried to use await Promise.all() around my mapping.

let foo = [1,2,3];

(async() => { 
   await Promise.all(foo.map(x => {
      return new Promise(async function(resolve) {
         await setTimeout(() => {
            console.log("X")
            resolve()
         }, 3000)
      });
   }))
})()

instead of sequentially getting a "X" log every 3 seconds, it's just waiting 3 seconds and then logging them all. I am not sure what I am doing wrong at this point.

kelsny
  • 23,009
  • 3
  • 19
  • 48
sal3jfc
  • 517
  • 4
  • 14
  • Promise.all is an all or nothing handler, if all the promises in it resolves then it finishes. So the expected behavior would be all the logs at one time. If one of the promises fail then they "all" fail and it will go into the reject of the promise – Colin Hale Aug 31 '22 at 19:58
  • All of the promises start at the same time, thus they resolve at the same time. – SuperStormer Aug 31 '22 at 19:59
  • 1
    Consider reading this post: [Is Node.js native Promise.all processing in parallel or sequentially?](https://stackoverflow.com/questions/30823653/is-node-js-native-promise-all-processing-in-parallel-or-sequentially) – Jeffrey Ram Aug 31 '22 at 20:00

1 Answers1

1

You are setting all the timeouts together at once. You need to increase the timeout duration in each iteration, maybe like this:

let foo = [1,2,3];

(async() => { 
   await Promise.all(foo.map((x, i) => {
      return new Promise(async function(resolve) {
         await setTimeout(() => {
            console.log("X")
            resolve()
         }, 3000 * (i + 1))
      });
   }))
})()
kelsny
  • 23,009
  • 3
  • 19
  • 48