SailsJs 调用函数到同一个控制器中

SailsJs call function into the same controller

我想在同一个控制器中调用一个函数,但我经常遇到如下错误:"ReferenceError: myFunctionB is not defined"

module.exports = {

    myfunctionA: function(req, res){

        var theword;
        theword = myFunctionB({id:26})

        return res.json({say:theword})

    }, 

    myfunctionB: function(req, res){

        var id = req.param('id');

        niceword.get({
            id:id
        }, function(err, word){

            if(err){return res.negotiate(err);}
            if(!word){return res.json({err:"no word found"})}

            return res.json({word:word});

        })

    }

}

我也尝试将 myFunctionB 放入服务中,但是,因为我使用了许多其他控制器等,所以我没有任何反应。有什么想法吗?

有几种方法可以做到这一点。正如 yBrodsky 所说,正确的方法是创建一个运行回调或 returns 承诺的服务:

myServiceFunctionB: function(params, cb) {
   var id = params.id;
   niceword.get({
        id:id
    }, function(err, word){
        return cb({ say: { word: word });
    });
}

然后在您的控制器中,只需使用:

return MyServiceName.myServiceFunctionB({id: 26}, res.json);

您也可以传入您的请求和资源以继续使用它们:

myServiceFunctionB: function(req, res) { ...

或者,您可以在控制器中使用 this 关键字:

myfunctionA: function(req, res){
    req.params.id = 26;
    return this.myfunctionB(req, res);
}

如果您要在上下文丢失的情况下执行更复杂的逻辑,只需在开始时使用以下命令设置一个新变量:

myfunctionA: function(req, res){
    var self = this;
    req.params.id = 26;
    //...lots of nested promises or callbacks...
         return self.myfunctionB(req, res);
}

谢谢 yBrodsky 和 ​​wwwslinge,谢谢你们,我终于得到了我需要的东西。

我不得不做一点改变,因为我仍然需要在它们传入函数后使用数据。

控制器

MyServiceName.functionB({id:1}, function(data){

    // doing some stuff with the data and then
    return res.json({data: data});

});

服务

functionB: function(params, cb){

    var id = params.id;

    Niceword.getbyid({
        id:id
    }, function(err, word){

         if(err){return err}
         return cb({word:word});

    })

}