Is forEach on an array async ? candies is an array of candy objects.
app.get('/api/:id',function(req, res){
console.log("Get candy");
var id = req.params.id;
candies.forEach( function(candy, index){
if(candy.id == id){
console.log("Candy found. Before return");
return res.json(candy);
console.log("Candy found. After return");
}
});
console.log("Print error message");
return res.json({error: "Candy not found"});
});
In the console I get
[nodemon] starting `node app.js`
listning on port 3000
Get candy
Candy found. Before return
Print error message
Error: Can't set headers after they are sent.
at ServerResponse.setHeader (_http_outgoing.js:367:11)
....
Is this a recent change ? It's been awhile since I have done node.js
return?Print error messagelogged first. Why would it be async? Also, Thilo pointed out correctly - what's the point of code afterreturnstatement? That will never be executed.returnin the inner function will only exit the inner function, not the outer one.