Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!