簡體   English   中英

MEAN Stack-查詢和請求延遲?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM