将异步请求组合到单个GET API中

时间:2019-06-26 11:21:18

标签: javascript node.js express request

我正在尝试为region参数在三种不同配置下调用GET API,并将结果组合到单个result对象中,我希望该API作为JSON返回。

这是我的方法,它使用一系列Promises。

app.get("/api/v2/leagues/games", (req, res) => {
  const regions = ['uk', 'us', 'au'];
  let result = {};

  let promiseArray = regions.map(region => {
    return new Promise((resolve, reject) => {
      const uri = `https://api.the-odds-api.com/v3/odds/?apiKey=${functions.config().theoddsapi.key}&sport=${req.query.league}&region=${region}&mkt=${req.query.mkt}`;
      console.log(uri);
      request.get(uri, (error, response, body) => {
        if (body) {
          result[region] = JSON.parse(body).data;
          resolve(body);
        }
        else {
          console.error("error:", error); 
          console.log("statusCode:", response && response.statusCode); 
          reject(error);
        }
      });
    });
  });

  Promise.all(promiseArray).then(() => {
    return res.json(result)
  }).catch(() => response.errorCode);
});
});

1 个答案:

答案 0 :(得分:0)

您使用的方法正确,但是您犯了一些错误。

尽管我尚未对其进行测试,但是下面的代码应该可以完成您想要的工作。

app.get("/api/v1/leagues/games", (req, res) => {
const promiseRequest = (sport, region, mkt) => {
return new Promise(resolve => {
    const theOddsApiUrl = `https://api.the-odds-api.com/v3/odds/?apiKey=${functions.config().theoddsapi.key}&sport=${sport}&region=${region}&mkt=${mkt}`; 
    request.get(theOddsApiUrl, (error, response, body) => {
    if (body) {
        resolve(body)
    }
    });
})
}
var sport = req.query.sport;
var mkt = req.query.mkt;

let allRegionsOdds = {};
Promise.all([
    promiseRequest(sport, 'uk', mkt),
    promiseRequest(sport, 'us', mkt),
    promiseRequest(sport, 'au', mkt)
]).then(body => {
    var response = allRegionsOdds[region] = body; // you can deide if this assignment is necessary or not for you
    res.json(response); // You want to return the response for the main Get after all the promises have been fulfilled.
}).catch(); // You can handle special cases in the catch, forexample when some promises fail.


//if you return the json at the end of function, your Promise.all hasn't gotten the time to be complete yet 
//and hence the variable response is still empty

//res.json(response);  

});