Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fixing error in implementing async/await in for loop(forEach of array) js

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 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
    }
}());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading