【发布时间】:2017-07-19 04:32:40
【问题描述】:
数组上的 forEach 是异步的吗? candies 是一个糖果对象数组。
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"});
});
在控制台中我得到
[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)
....
这是最近的变化吗?自从我完成 node.js 以来已经有一段时间了
【问题讨论】:
-
为什么
return后面有代码? -
如果它是异步的,您将首先记录
Print error message。为什么会是异步的?此外,Thilo 正确指出了 -return语句之后的代码有什么意义?那永远不会被执行。 -
另外,内部函数中的
return只会退出内部函数,不会退出外部函数。 -
啊,我们走了……当然!完美的解释了它。我今天一定想不通。谢谢@Thilo!
标签: javascript arrays node.js nodes