繁体   English   中英

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

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

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

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的建议,我查看了:

Node.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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM