'fixing error in implementing async/await in for loop(forEach of array) js [duplicate]

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 :)



Solution 1:[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)
    }
}());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prashant G