我如何访问Mongoose / nodejs中的callback函数内的值?

我写了一个函数,它使用Mongoose从mongoDB中读取一个项目,并且我想把结果返回给调用者:

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; }; 

但是,正如您所看到的,结果仅在“findOne”的callback函数中有效。 我只需要将“item”的值返回给调用者函数,而不是在callback函数中进行任何处理。 有没有办法做到这一点?

非常感谢你!

因为你在函数中进行asynchronous调用,所以你需要为GetItemBySku方法添加一个callback参数,而不是直接返回该项。

 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时,该值将在callback函数中返回。 例如:

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