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

122
Visualizações
Node.js - forEach loop inside Try - Catch block

When I have:

try {
  array.forEach(items => {
    //do something
    //here something is going wrong
  })
  res.status(200).json({
    success: true
  })
} catch (err) {
  res.status(400).json({
    message: err.message
  })
}

Error is not catching - I've got 200 response but I can see crashed app and on terminal I have error. But this error is not catched by catch(err) block.

But if I have For of loop I'm getting 400 response.

Erros is the same - in forEach it is not catched and response is ok but in for of loop erros is catched and I have 400 response with error. Why? Why I can't catch error in forEach and send 400 res by catch block?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Short answer:

This is designed for JS forEach.


Longer one:

Note: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

From MDN Web Docs Array.prototype.forEach()

BTW, it does not wait for promise as well.

forEach does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as forEach callback.


In sum,

  • This probably confuses many JS developers, but in design, this is how JS works.
  • For avoid the similar issues, try not using forEach, use for or while
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