简体   繁体   English

MEAN Stack-查询和请求延迟?

[英]MEAN Stack - Delay in query and request?

I'm trying to learn Node.js and writing a web app with the MEAN stack. 我正在尝试学习Node.js,并使用MEAN堆栈编写一个Web应用程序。

As I send on an array of strings containing item data (say, ["one", "two", "three"] ) to the server side, I have the following code to iterate through the array, check if a document with the element already exists in MongoDB, then accordingly create new documents in the database. 当我向服务器端发送包含项目数据(例如["one", "two", "three"] )的字符串数组时,我具有以下代码来遍历该数组,检查是否有包含元素已经存在于MongoDB中,然后相应地在数据库中创建新文档。

server side code: 服务器端代码:

// 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;
                });
            }
        });
    }
}

The problem is that new_item.name always equals the last element in the array, ie "three" 问题是new_item.name始终等于数组中的最后一个元素,即"three"

My guess is that the query in the database takes longer than the loop to run, so by the time we're in the callback of findOne() , we've already iterated to the end of the array. 我的猜测是数据库中的查询所花的时间比循环要长,因此,当我们进入findOne()的回调时,我们已经迭代到数组的末尾。

Is this true? 这是真的? If so, what would be a work around for this problem? 如果是这样,该问题将如何解决?

I understand that this is potentially be a common question that many may have asked before, but after some time of searching I'm still not able to solve the problem. 我了解到,这可能是许多人以前曾问过的一个常见问题,但是经过一段时间的搜索,我仍然无法解决问题。 Please advise. 请指教。

There's already a comment that says to do this. 已经有一条评论说要这样做。 You can create closure (as below) or create a separate function that's outside of the loop. 您可以创建闭包(如下所示),也可以创建循环外的单独函数。 Here's a little blog post about closures http://jondavidjohn.com/blog/2011/09/javascript-closure-explained-using-events 这是有关封包的小博文,网址为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM