Jens Jens -4 years ago 167
Node.js Question

Is Array.forEach in Node.js asynchronous?

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

Answer Source

You're getting the Can't set headers after they are sent. exception because you're trying to return a response twice - (possibly) once inside candies.forEach and once again in the last line of the route. Also note that any code after a return isn't executed anyways.

Here's how you rewrite it to avoid the error —

app.get('/api/:id',function(req, res){

    console.log("Get candy");
    var id = req.params.id;
    var foundCandy = false;
    candies.forEach( function(candy, index){
        if(candy.id == id){
            foundCandy = true;
            console.log("Candy found. Before return");
        }
    });

    if (foundCandy) {
        return res.json(candy);
    } else {
        return res.json({error: "Candy not found"});
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download