2015-07-10 38 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()