MEAN Stack - 延迟查询和请求?

时间:2014-03-04 22:45:33

标签: java ajax node.js mongodb web

我正在尝试学习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()的回调时,我们已经迭代到数组的末尾。 / p>

这是真的吗?如果是这样,那么解决这个问题的方法是什么?

我知道这可能是许多人之前可能会提出的一个常见问题,但经过一段时间的搜索,我仍然无法解决问题。请指教。

1 个答案:

答案 0 :(得分:0)

已有评论说这样做。您可以创建闭包(如下所示)或创建一个在循环外部的单独函数。这是关于闭包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]);
}