'Node.js - forEach loop inside Try - Catch block [duplicate]
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?
Solution 1:[1]
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, usefororwhile
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tim |
