I have an application that needs to request NASA's Astronomy Picture of the Day 5 times and then it will load a webpage displaying those images. I then request a different site (the LaunchLibrary API) to get the next 5 launches. My problem is when I have to display the image; sometimes it will display 2 images, sometimes 5, sometimes none. This is obviously just the asynchronous nature of GET requests but I was wondering if there is a way to wait for the NASA pictures before rendering the page.
Here is an example of what I have.
app.get("/index", function(req, res) {
/**Requesting NASA's Astronomy Picture of the Day**/
var apod_url = "https://api.nasa.gov/planetary/apod?api_key=[My API Key]"
var apod_img_urls = [];
var curr_moment = moment();
for(var i = 0; i < 5; i++) {
var appended_url = apod_url + "&date=" + curr_moment.subtract(i, "days").format("YYYY-MM-DD");
request(appended_url, function(error, reponse, body) {
if(!error && reponse.statusCode == 200) {
var img_json = JSON.parse(body);
apod_img_urls.push(img_json.hdurl);
} else {
console.log(error);
}
});
}
/**************************************************/
var url = "https://launchlibrary.net/1.3/launch/next/5";
request(url, function(error, response, body) {
if(!error && response.statusCode == 200) {
var data = JSON.parse(body);
res.render("index", {data: data, apod_img_urls: apod_img_urls});
} else {
console.log(error);
}
});
});
I've also tried putting the loop of image requests inside of the if-statement in my request for the next 5 launches and that caused none of the images to show up. Is there a way I can "synchronize" these requests so all of the images return before rendering the page?