Node.js 如何访问Mongoose/nodejs中回调函数中的值?
我编写了一个函数,使用Mongoose从mongoDB读取一个项,并希望将结果返回给调用方:Node.js 如何访问Mongoose/nodejs中回调函数中的值?,node.js,callback,mongoose,Node.js,Callback,Mongoose,我编写了一个函数,使用Mongoose从mongoDB读取一个项,并希望将结果返回给调用方: ecommerceSchema.methods.GetItemBySku = function (req, res) { var InventoryItemModel = EntityCache.InventoryItem; var myItem; InventoryItemModel.findOne({'Sku' : req.query.sku}, function (err
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”的回调函数中有效。我只需要将“item”的值返回给调用者函数,而不是在回调函数中进行任何处理。有没有办法做到这一点
多谢各位 因为在函数中执行异步调用,所以需要向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)
}
});
因为在函数中执行异步调用,所以需要向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)
}
});