[英]Is Array.forEach in Node.js asynchronous?
數組上的forEach是否異步? 糖果是一系列糖果對象。
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以來已經有一段時間了
Can't set headers after they are sent.
您將收到“ Can't set headers after they are sent.
例外,因為您嘗試返回兩次響應(可能),一次是在candies.forEach
, candies.forEach
一次是在路線的最后一行。 還要注意, return
后的任何代碼都不會執行。
這是您如何重寫以避免錯誤的方法-
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"});
}
});
您可以使用Array.filter找到糖果。
app.get('/api/:id', function(req, res) {
console.log("Get candy");
var id = req.params.id;
var result = candies.filter(candy => candy.id == id);
if (result.length) {
return res.json(result[0]);
} else {
console.log("Print error message");
return res.json({
error: "Candy not found"
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.