타사 API에 여러 요청을 한 다음 수신 한 데이터 배열을 다시 보내야하는 프로젝트에서 작업하고 있습니다. 고객. 분명히 제 3 자 API에 대한 요청은 비동기이며 요청 루프 바로 다음에 res.json을 놓으면 데이터가 비어있게됩니다. 요청서를 약속대로 포장해야합니까? 제안 @ jfriend00의 당으로타사 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