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()被調用?
在此先感謝您的幫助!
的可能重複[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – victorkohl
什麼是「完成」功能? –
簡短的回答:你不能。另見:http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – JohnnyHK