Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

235
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda