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

197
Views
Javascript - why its not possible to make function inside for look synchronous using async/await?

Im sorry for the question since there are already many similar questions. However, I still dont understand. The code below is suppose to show HOW to make a for loop act synchronous. However, as I see it its still not snychronous. The output of the code below is ** 1 2 3 after forEach done **

But I wonder, if we put the await keyword in front of the function, why is the output not:

** 1 after forEach 2 after forEach 3 after forEach done **

? Because result holds one num at a time, waiting for the execution of returnNum.

const asyncFunction = async () => {
  const nums = [1, 2, 3];

  for (const num of nums) {
    const result = await returnAsyncNum(num);
    console.log(result);
  }

  console.log('after forEach');
}

const returnAsyncNum = x => {
  return new Promise(resolve => setTimeout(resolve, 500, x));
}

asyncFunction().then(() => {
  console.log('done');
})

almost 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The console.log('after forEach') will only execute once the for is fully completed. That does makes sense since you are letting it after the for of, doesn't it?

If you put a console.log before the resolve(x), you will see how the code is waiting for the promise to return the number.

almost 4 years ago · Santiago Trujillo Report

0

That's point of async functions, they allow you to write async code as if it were sync.
You are waiting for the promise to complete and get its value.
Since you are waiting for the Promise, the execution of the async function stops in the await and when the Promise fulfills you get its value and the execution continues.

Also your expected output does not make any sense, console.log('after forEach') can only log once by calling the function once.

almost 4 years ago · Santiago Trujillo 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!