Reputation: 513
I wrote a function that reads an item from mongoDB using Mongoose, and i want the result to be returned to the caller:
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;
};
However as you can see, the result is only valid in the callback function of "findOne". I only need the value of "item" to be returned to the caller function, instead doing anything processing in the callback function. Is there any way to do this?
Thank you very much!
Upvotes: 1
Views: 1261
Reputation: 3247
Because you're doing an asynchronous call in the function, you'll need to add a callback argument to the GetItemBySku method rather than returning the item directly.
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)
});
};
Then when you call GetItemBySku in your code, the value will be returned in the callback function. For example:
eCommerceObject.GetItemBySku(req, res, function (err, item) {
if (err) {
console.log('An error occurred!');
}
else {
console.log('Look, an item!')
console.log(item)
}
});
Upvotes: 1