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

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

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 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