2013-01-14 65 views
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」的值返回給調用者函數,而不是在回調函數中進行任何處理。有沒有辦法做到這一點?

非常感謝!

回答

1

因爲你正在做的功能的異步調用,你需要一個回調參數添加到GetItemBySku方法,而不是直接返回該項目。

ecommerceSchema.methods.GetItemBySku = function (req, res, callback) { 
    var InventoryItemModel = EntityCache.InventoryItem; 

    InventoryItemModel.findOne({'Sku' : req.query.sku}, function (err, item) { 
     if (err) { 
      return callback(err); 
     } 
     callback(null, item) 
    }); 
}; 

然後當你調用GetItemBySku在你的代碼,該值將在回調函數返回。例如:

eCommerceObject.GetItemBySku(req, res, function (err, item) { 
    if (err) { 
     console.log('An error occurred!'); 
    } 
    else { 
     console.log('Look, an item!') 
     console.log(item) 
    } 
}); 
相關問題