如何在向第三方 API 节点发出多个请求后发送响应.js.

How to send a response after making multiple requests to a third party API Node.js

本文关键字:请求 js 响应 第三方 API 节点      更新时间:2023-09-26

我正在做一个项目,我需要向第三方API发出多个请求,然后将收到的数据数组发回给客户端。显然,对第三方 API 的请求是异步的,如果我在请求循环之后立即放置 res.json,数据将为空。我是否需要将请求包装在承诺中?这是我的代码:

const historicalForecast = (req, res, next) => {
  console.log(req.body);
  // GET COORDS FROM GOOGLE API BY LOCATION INPUT BY USER
  let googleUrl = `https://maps.googleapis.com/maps/api/geocode/json?address=${req.body.input}&key=${googleKey}`;
  request(googleUrl, function(error, response, body){
    if(error){
      console.log(error);
      next();
    }
    let data = JSON.parse(response.body);
    //IF MORE THAN ONE RESULT FROM GEOLOCATION QUERY
    //ADD DATES REQUESTED INTO RESPONSE AND
    //SEND LIST OF LOCATIONS BACK SO USER CAN CHOOSE
    if(data.results.length > 1){
      response.body.startDate = req.body.startDate;
      response.body.endDate = req.body.endDate;
      res.json(JSON.parse(response.body));
    //IF ONE RESULT, GET DATA IN BATCHES
    }else if(data.results.length === 1) {
      let coords = data.results[0].geometry.location;
      const OneDay = 86400;
      let timeFrame = Math.abs(req.body.startDate - req.body.endDate);
      let numberOfDays = timeFrame/OneDay;
      console.log(numberOfDays);
      let results = [];
      for(let i = 0; i < numberOfDays; i++){
        let currentDay = Number(req.body.startDate) + (i*OneDay);
        let urlWeather = `https://api.forecast.io/forecast/${weatherKey}/${coords.lat},${coords.lng},${currentDay}`;
        request(urlWeather, function(error, response, body){
          if(error){
            console.log(error);
            next();
          }
          results.push(JSON.parse(response.body));
          res.send(results);
        });
      }
    }
  });
};

根据@jfriend00的建议,我看了一下:

节点.JS如何在当前范围之外设置变量

并使用了那里提供的众多选项之一。我的解决方案在上面的帖子中。将为该帖子添加书签以备将来参考。

我将 else if 语句中的所有代码替换为:

  let coords = data.results[0].geometry.location;
  const OneDay = 86400;
  let timeFrame = Math.abs(req.body.startDate - req.body.endDate);
  let numberOfDays = timeFrame/OneDay;

  const makeMultipleQueries = (url) => {
    return new Promise(function(resolve, reject) {
      request(url, function(error, response, body){
        if(error){
          reject(error);
        }
        resolve(response.body);
      });
  });
};
let promises = [];
for (let i = 0; i < numberOfDays; i++) {
  let currentDay = Number(req.body.startDate) + (i*OneDay);
  let url = `https://api.forecast.io/forecast/${weatherKey}/${coords.lat},${coords.lng},${currentDay}`;
  promises.push(makeMultipleQueries(url));
}
Promise.all(promises).then(function(results) {
    res.json(results);
}, function(err) {
    next(err);
});