forEachは配列asyncで使用しますか?キャンディーはキャンディーオブジェクトの配列です。コンソールでNode.jsのArray.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)
....
を取得し、これは最近の変更ですか?
なぜあなたは 'return'の後にコードを持っていますか? – Thilo
もしそれが非同期だったら、 'Print error message'が最初に記録されます。なぜそれは非同期でしょうか?また、Thiloは正しく述べています - 'return'ステートメントの後のコードのポイントは何ですか?それは決して実行されません。 – Mjh
また、内部関数の 'return'は、内部関数を終了するだけで、内部関数は終了しません。 – Thilo