对于某条路线,我有以下代码:
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
的路由中使用该返回的对象。我哪里错了?
答案 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()