【问题标题】:How do i access the value within callback function in Mongoose/nodejs?如何访问 Mongoose/nodejs 回调函数中的值?
【发布时间】:2012-12-28 12:33:55
【问题描述】:

我编写了一个使用 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”的回调函数中有效。我只需要将“item”的值返回给调用者函数,而不是在回调函数中进行任何处理。有没有办法做到这一点?

非常感谢!

【问题讨论】:

    标签: node.js callback mongoose


    【解决方案1】:

    由于您在函数中进行异步调用,因此您需要向 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时,这个值会在回调函数中返回。例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-13
      • 2016-08-09
      • 2021-06-01
      • 2020-07-31
      • 1970-01-01
      • 2022-01-26
      相关资源
      最近更新 更多