2017-08-10 143 views
1

我想讓這個函數做一個適當的回調。正如所寫,回調將被調用兩次 - 一次用於同步「if」語句,一次用於異步「test2.save」語句。我正在將計數器代碼作爲我嘗試的一個示例。它不起作用,因爲底部if語句是同步的。我已經知道這段代碼有什麼問題,但我不知道如何使它更好。在mongodb函數上的異步回調

var postMatches = function(user1, userResults, callback) { 
    User.find({}, {username: 1, testResults: 1}, (err, users) => { 
    var counter = 0; 
    users.forEach(function(user2){ 
     counter++; 
     if(user1 !== user2.username && user2.testResults !== undefined) { 
     var test1 = new Test({ 
      username: user1, 
      match: user2.username, 
      compatability: mbti[userResults][user2.testResults], 
      alreadyMatches: false 
     }); 

     test1.save(() => { 
      var test2 = new Test({ 
      username: user2.username, 
      match: user1, 
      compatability: mbti[user2.testResults][userResults], 
      alreadyMatches: false 
      }); 

      test2.save(() => { 
      if(counter === users.length) { 
       callback(); 
      } 
      }); 
     }) 
     } else { 

     if(counter === users.length) { 
      callback(); 
     } 
     } 
    }) 
    }) 
}; 
+0

你的用例是什麼?基本上你想達到什麼目的?我可以得到的是你有一個數據庫的用戶,並試圖匹配一些輸入用戶的基礎上的一些參數,你能解釋一個litle。 –

+0

該函數在Test集合中創建兩個用戶之間的鏈接。我需要回調函數來測試函數。我不需要爲我的應用程序的回調工作,但我認爲這是一個非常有趣的情況,並希望聽到一些想法。 – Marc

+0

你想達到什麼目的?如果user1不匹配user2,則保存鏈接,否則返回回調函數?爲什麼要從test2.save調用回調函數? –

回答

1

從評論和問題,在這裏編譯代碼。使用異步模塊和forEach函數迭代用戶列表並返回一次完成的回調。閱讀有關async和forEach的信息。讓我知道這是否適用於您的用例。

var async = require('async') 
var postMatches = function(user1, userResults, callback) { 
    User.find({}, {username: 1, testResults: 1}, (err, users) => { 
    var counter = 0; 
    async.forEach(users,function(user2,iterate_callback){ 
     if(user1 !== user2.username && user2.testResults !== undefined) { 
     var test1 = new Test({ 
      username: user1, 
      match: user2.username, 
      compatability: mbti[userResults][user2.testResults], 
      alreadyMatches: false 
     }); 

     test1.save(() => { 
      var test2 = new Test({ 
      username: user2.username, 
      match: user1, 
      compatability: mbti[user2.testResults][userResults], 
      alreadyMatches: false 
      }); 

      test2.save(() => { 
      iterate_callback(); 
      }); 
     }) 
     } else { 
     iterate_callback(); 
     } 
    },function(err){ 
     console.log("Done iterating"); 
     return callback(); 
    }); 
    }) 
}; 
+0

test2.save -callback應該調用iterate_callback,否則forEach永遠不會結束? – mtkopone

+0

編輯答案。你得到它正確的人:) –

+0

這工作像一個魅力。我不知道異步的foreach。感謝您的教訓。 – Marc