[英]MEAN Stack - Delay in query and request?
我正在尝试学习Node.js,并使用MEAN堆栈编写一个Web应用程序。
当我向服务器端发送包含项目数据(例如["one", "two", "three"]
)的字符串数组时,我具有以下代码来遍历该数组,检查是否有包含元素已经存在于MongoDB中,然后相应地在数据库中创建新文档。
服务器端代码:
// items is an array of strings sent from the client side
for (var i = 0; i < items.length; i++) {
var item_name = items[i];
// For each item, find an existing one
Item.findOne({'name': item_name }, function(err, item) {
// If not already existing, add to database.
if (!item) {
var new_item = new Item();
new_item.name = item_name;
new_item.save(function(err) {
if (err) throw err;
});
}
});
}
}
问题是new_item.name
始终等于数组中的最后一个元素,即"three"
我的猜测是数据库中的查询所花的时间比循环要长,因此,当我们进入findOne()
的回调时,我们已经迭代到数组的末尾。
这是真的? 如果是这样,该问题将如何解决?
我了解到,这可能是许多人以前曾问过的一个常见问题,但是经过一段时间的搜索,我仍然无法解决问题。 请指教。
已经有一条评论说要这样做。 您可以创建闭包(如下所示),也可以创建循环外的单独函数。 这是有关封包的小博文,网址为http://jondavidjohn.com/blog/2011/09/javascript-closure-explained-using-events
// items is an array of strings sent from the client side
for (var i = 0; i < items.length; i++) {
(function(item_name) {
// For each item, find an existing one
Item.findOne({'name': item_name }, function(err, item) {
// If not already existing, add to database.
if (!item) {
var new_item = new Item();
new_item.name = item_name;
new_item.save(function(err) {
if (err) throw err;
});
}
});
})(items[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.