【问题标题】:How to return Node.js callback如何返回 Node.js 回调
【发布时间】:2015-07-16 07:17:32
【问题描述】:

我有一个 node.js 方法,它使用 mongoose 来返回一些数据,问题是因为我在我的方法中使用回调,所以没有任何东西返回给客户端

我的代码是:

var getApps = function(searchParam){
    var appsInCategory = Model.find({ categories: searchParam});
    appsInCategory.exec(function (err, apps) {
        return apps;
    });
}

例如,如果我尝试使用 json 对象同步执行此操作,它将起作用:

var getApps = function(searchParam){
    var appsInCategory = JSONOBJECT;
    return appsInCategory
} 

我能做什么?

【问题讨论】:

    标签: node.js mongodb asynchronous callback mongoose


    【解决方案1】:

    您无法从回调中返回 - 请参阅 this canonical about the fundamental problem。由于您正在使用 Mongoose,因此您可以为它返回一个承诺:

    var getApps = function(searchParam){
        var appsInCategory = Model.find({ categories: searchParam});
        return appsInCategory.exec().then(function (apps) {
            return apps; // can drop the `then` here
        });
    }
    

    这会让你做什么:

    getApps().then(function(result){
        // handle result here
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2021-08-17
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多