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