我正在使用nodejs從MongoDB到Mongoose查詢數據。 獲取數據後,我希望在對客戶端進行響應之前對數據進行一些操作。但我無法獲得回報價值。在Google上查看之後,我瞭解到Node.js函數是異步JavaScript函數(非I/O阻塞)。我嘗試這個嘖嘖(http://www.youtube.com/watch?v=xDW9bK-9pNY),但它不工作。以下是我的代碼。 myObject在「find()」函數內部被賦值,而在「find()」函數外被undefined賦值。那麼我應該怎麼做才能獲得數據?謝謝!Nodejs中異步函數的返回值
var Person = mongoose.model('Person', PersonSchema);
var Product = mongoose.model('Product', ProductSchema);
var myObject = new Object();
Person.find().exec(function (err, docs) {
for (var i=0;i<docs.length;i++)
{
Product.find({ user: docs[i]._id},function (err, pers) {
myObject[i] = pers;
console.log(myObject[i]); //return the value is ok
});
console.log(myObject[i]); //return undefined value
}
console.log(myObject); //return undefined value
});
console.log(myObject); //return undefined value
app.listen(3000);
console.log('Listening on port 3000');
這是我的帖子從github:https://github.com/LearnBoost/mongoose/issues/1706#issuecomment-24887415 –