0

I'm trying to create a loop with .map() that iterate an array of numbers I want to log each numbers of this array with a delay between each iterations When I do that, all of my numbers are instantly logged on the console without a delay

Any idea of what is happening here ? What am I missing ?

I tried to write my loop with a basic for(i) but I got only the first number to show up.

(async () => {

  var numbers = [7, 3, 6, 9, 4, 8];

  await Promise.all(numbers.map(async n => {
    console.log(n);
    await delay(3000);
  }));
  console.log('done');

})();

function delay(time) {
  return new Promise(resolve => {
    setTimeout(resolve, time);
  });
}

Here is a code snippet: https://playcode.io/373435?tabs=script.js,preview,console

The console shows:

7
3
6
9
4
8
'done'

I excepted to be a delay between each iterations but all of the numbers are instantly logged on the console without a delay

Tim
  • 41
  • 2
  • 10
  • 1
    Each `.map` callback initializes immediately. Use a `for` loop instead (don't use `for..in` to iterate over arrays, use `for..of` or a basic `for`) – CertainPerformance Jul 14 '19 at 02:07
  • Thank you for your fast reply. Sorry for the typo, a basic `for(i)` was giving me just one number and stopped I tried with a `for..of`: same as the basic for But with a `for..in` it worked! – Tim Jul 14 '19 at 02:15

0 Answers0