1
我寫了一個函數讀取使用貓鼬從MongoDB的一個項目,我想要的結果返回給調用者:如何訪問Mongoose/nodejs中的回調函數中的值?
ecommerceSchema.methods.GetItemBySku = function (req, res) {
var InventoryItemModel = EntityCache.InventoryItem;
var myItem;
InventoryItemModel.findOne({'Sku' : req.query.sku}, function (err, item) {
// the result is in item
myItem = item;
//return item doesn't work here!!!!
});
//the value of "myItem" is undefined because nodejs's non-blocking feature
return myItem;
};
但是你可以看到,結果是隻有在回調函數有效「找一個」。我只需要將「item」的值返回給調用者函數,而不是在回調函數中進行任何處理。有沒有辦法做到這一點?
非常感謝!