我正在做一个项目,我需要向第三方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的建议,我查看了:
并使用那里提供的众多选项之一。我的解决方案在上面的帖子中。将为该帖子添加书签,以备将来参考。
我将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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句