Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda