2015-07-10 28 views
0

对于特定的路线,我有以下代码:ExpressJS - 运用Q

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请求到我的URL与适当的参数等

当我加载/:id,我看到“返回与代码200”记录,但“异步回”不是日志GED。我也不确定响应是否正在发送。

一旦GetGames返回一些东西,我希望能够在路由中使用那个返回的对象/:id。我哪里错了?

回答

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()