2015-04-28 27 views
1

我試圖從執行mongodb查詢的函數返回一個值。 我的問題是該函數沒有返回任何內容,因爲查詢在返回之前沒有完成。node.js函數應該只在MongoDB查詢完成後返回

如果我嘗試console.log(checkChickenValue(2));例如我得到undefined回來。這裏是相關的功能:

function checkChickenValue(chickenid) { 
    MongoClient.connect(url, function(err, db) { 

     var cursor = db.collection('games').find({}, { 
      limit : 1, 
      fields : { 
       _id : 1 
      }, 
      sort : { 
       _id : -1 
      } 
     }).toArray(function(err, docs) { 
      var id = docs[0]._id; 
      var test = db.collection('games').findOne({ 
       _id : id 
      }, function(err, result) { 
       switch(chickenid) { 
       case 1: 
        complete(result.chicken1.value); 
        break; 
       case 2: 
        complete(result.chicken2.value); 
        break; 
       case 3: 
        complete(result.chicken3.value); 
        break; 
       case 4: 
        complete(result.chicken4.value); 
        break; 
       case 5: 
        complete(result.chicken5.value); 
        break; 
       case 6: 
        complete(result.chicken6.value); 
        break; 
       case 7: 
        complete(result.chicken7.value); 
        break; 
       case 8: 
        complete(result.chicken8.value); 
        break; 
       } 

      }); 

     }); 
    }); 
    function complete (value) 
    { 
     return value; 
    } 
}; 

我該如何讓函數等到complete()被調用?

在此先感謝您的幫助!

+0

的可能重複[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – victorkohl

+0

什麼是「完成」功能? –

+0

簡短的回答:你不能。另見:http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – JohnnyHK

回答

3

您需要通過回調返回結果。爲你的函數添加一個'callback'參數,表示一個函數,當結果準備就緒時會被調用。

function checkChickenValue(chickenid, callback) 
{ 

然後,當你有結果,通過回調返回它:

switch(chickenid) { 
    case 1: 
     callback(complete(result.chicken1.value)); 

然後,用你的功能,做這樣的事情:

checkChickenValue(2, function(result){ console.log(result); }); 
+0

非常感謝你,這有幫助我很多! :) – babadaba

相關問題