我正在使用Node.js编写一个简单的应用程序。我没有使用框架(以了解它在"较低"级别的工作方式(。
我想做什么:
当GET请求发送到"/list"时,我使用我的MongoDB连接来执行find((。然后我想遍历每个返回的项目,并使用 response.write(">
" + myItem
( 显示它们。问题是我需要在最后执行一个response.end((,我不知道"结束"是什么时候——因为我所有的response.write((语句都是使用回调执行的。
这是我的代码:
db.items.find({state: "free"}, function(err, myItems) {
if (err) {
console.log("There was an error executing the database query.");
response.end();
return;
}
else if (myItems){
myItems.forEach( function(myItem) {
res.write("<p>" + myItem.title + "</p>n");
});
}
res.write("</div>");
res.end();
}
我感觉我在这里缺少一种使用回调的惯用方式......解决此问题的干净方法是什么?
谢谢!
这是正确的方式,你的 end(( 将在回调结束时被调用,所以在你的 foreach 循环之后,函数将继续发送 end(( 方法。或者也许我错过了你问题的重点。但我认为不是。