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

234
Views
Why is foreach behaving asynchronously?

I am learning node.js and I am confused about how async works. My understanding is that Array.foreach is blocking but then the below piece of code does not work as expected.

testfunc.ts:

export const testfunc = async (numArray: number[]) => {
  let count = 0;
  numArray.forEach(async (elem) => {
    if (elem % 2 === 0) {
      await new Promise((r) => setTimeout(r, 2000));
      console.log(elem);
      count = count + 1;
    }
  });
  console.log(`printed ${count}`);
};

sendmessage.ts:

import { testfunc } from "./testfunc";

const callTestFunc = async () => {
  await testfunc([1, 2, 3, 4, 5, 6]);
};

callTestFunc();

I was expecting an out put of:

2
4
6
printed 3

But, I am getting

printed 0
2
4
6

Can someone explain this to me.

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

0

With forEach, you do your stuff in a callback function and this callback is taking some times. So it's asynchronous.

Consequently, forEach can't be used for synchronous tasks.

This is also the same for a for loop which is calling a function which is asynchronous. For example, if you execute a SQL INSERT query inside a for loop, you can not be sure that INSERT are executed in the loop order.

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!