1

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!

1 Answer 1

1

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)
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.