节点js - 如何访问同一控制器中的另一个函数

时间:2017-01-12 12:14:21

标签: javascript node.js express

我有两个功能,我无法从功能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

谢谢

1 个答案:

答案 0 :(得分:1)

使用 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