0

while running this code i get output of

1
3
2

my intented output is

1
2
3

const test = [1, 2, 3]
test.forEach(async (i) => {
   if (i === 2) {
      await new Promise(resolve => setTimeout(resolve, 3000));
   }
   console.log(i);
 })

how do i make the print statement to wait 3s if i === 2 if you can pls explain too :)

pilchard
  • 12,414
  • 5
  • 11
  • 23
KiNgSlAyEr
  • 11
  • 5

1 Answers1

1

You cannot use .forEach to execute sequentially because the Promise returned to the forEach function is ignored. You have to use for...of loop.

Here's an example:

const test = [1, 2, 3];

(async function () {
    for (let i of test) {
        if (i === 2) {
            await new Promise(resolve => setTimeout(resolve, 3000));
        }
        console.log(i)
    }
}());
Prashant Ghimire
  • 4,890
  • 3
  • 35
  • 46