ExpressJS - 使用Q.

时间:2015-07-10 03:23:54

标签: node.js express q node-request

对于某条路线,我有以下代码:

router.get('/:id', function(req, res) {
  var db = req.db;
  var matches = db.get('matches');
  var id = req.params.id;

  matches.find({id: id}, function(err, obj){
    if(!err) {
      if(obj.length === 0) {
        var games = Q.fcall(GetGames()).then(function(g) {
          console.log("async back");
          res.send(g);
        }
          , function(error) {
            res.send(error);
          });
      }
      ...
});

函数GetGames定义如下:

function GetGames() {
  var url= "my-url";
  request(url, function(error, response, body) {
    if(!error) {
      console.log("Returned with code "+ response.statusCode);
      return new Q(body);
    }
  });
}

我使用request模块通过适当的参数等向我的网址发送HTTP GET请求。

当我加载/:id时,我看到"返回代码200"记录,但" async back"未记录。我也不确定是否发送了回复。

一旦GetGames返回某些内容,我希望能够在/:id的路由中使用该返回的对象。我哪里错了?

1 个答案:

答案 0 :(得分:1)

由于GetGames是异步函数,因此请将其写入node.js回调模式:

function GetGames(callback) {
  var url= "my-url";
  request(url, function(error, response, body) {
    if(!error) {
      console.log("Returned with code "+ response.statusCode);
      return callback(null,body)
    }
    return callback(error,body)
  });
}

然后使用Q.nfcall调用上述函数并返回一个承诺:

 Q.nfcall(GetGames).then(function(g) {
 })
 .catch()