我有两个函数,但无法从函数 2 访问函数 1。 我怎样才能做到这一点?
class firstController
{
one(req, res)
{
var stamp = request.query("Select 'ALB'+left(newid(),5)+right(newid(),5)+ left(newid(),5)+right(newid(),5) as stamp");
Promise.all([stamp]).then(function(listOfResults)
{
var data = listOfResults[0][0].stamp;
res.send(data);
}).catch(function(err)
{
// ... query error checks
console.log(err);
});
}
two(req, res){
//get the data returned from function 1
console.log(this.one(req, res));
}
}
module.exports = firstController;
我有这个错误:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'getStamp' of undefined
谢谢
最佳答案
使用 this 访问 ES6 中同一类中的函数。与其他语言相比,ES5 和 ES6 中的这一点相当复杂,我建议您看一下。
class firstController
{
one(req, res)
{
res.send("hello");
}
two(req, res){
this.one(req, res);
}
}
module.exports = firstController;
更新 要将数据从一变为二,您需要像这样返回 Promise 的结果
one(req, res) {
var stamp = request.query("Select 'ALB'+left(newid(),5)+right(newid(),5)+ left(newid(),5)+right(newid(),5) as stamp");
return Promise.all([stamp]).then(function(listOfResults) {
return listOfResults[0][0].stamp;
}).catch(function(err) {
// ... query error checks
console.log(err);
return err;
});
}
two(req, res){
//get the data returned from function 1
console.log(this.one(req, res));
}
只有当你想返回数据给客户端时才使用res.send
关于javascript - Node js - 如何访问同一 Controller 中的另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41612984/