我正在開發一個項目,我需要向第三方API發出多個請求,然後將收到的數據發回給客戶。顯然,對第三方API的請求是異步的,如果我在請求循環之後立即放置res.json,數據將是空的。我是否需要在承諾中包裝請求?這裏是我的代碼:如何在向第三方API發出多個請求後發送響應Node.js
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);
});
}
}
});
};
你將要使用request'的'一個promisified版本,然後使用'Promise.all()'當所有請求知道完成。這個問題之前可能已經被提過很多次了,所以這裏可能有很多其他的解釋。 – jfriend00
下面是使用承諾知道何時完成多個異步操作的一般結構:http://stackoverflow.com/questions/32799672/node-js-how-to-set-a-variable-outside-the-current-scope/32799727#32799727 – jfriend00
謝謝你的建議。 @ jfriend00 – Atache