I'm wondering how to store the response data from an asynchronous xmlhttprequest in a variable to be used after the request has finished? Is this even best practice or should i make all operations that depends on the response data inside of the request?
I'm thinking the xmlhttprequest should only return the data and other operations related to the data should be made after the request has been completed. Or am i getting this wrong?
I cannot post the whole code but hopefully the comments explains what i want to do. In the bellow example i make an synchronous get request to a weather forecast API. The response contains forecasts for more than 24 hours but i only plan to use 3 forecasts from the response to cover todays weather. However each forecast contains a symbol id that i need in order to get the correct weather image for the report. This means that i will have to store those 3 id's so that i can build the correct URL.s in order to get the corresponding images for the forecasts. Even though this works synchronously i rather do it asynchronously as it seem to be recommended.
The problem here is that i need to store the response data from the xmlhttprequest in some variable so that i can use the symbol id's from the response to build the URL:s for the corresponding weather images.
let baseURL = 'https://api.met.no/weatherapi';
let forecastBase = 'locationforecast/1.9';
let latitude = 'lat=40.730610';
let longitude = 'lon=-73.935242';
let forecastURL = baseURL + '/' + forecastBase + '/' + '?' + latitude + '&' + longitude;
let weatherData;
const xhttp = new XMLHttpRequest();
document.addEventListener("DOMContentLoaded", function(event) {
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// GET the forecast reports and the symbol id for the weather images
}
}
xhttp.open('GET', forecastURL, false);
xhttp.send();
// Get weather images with the symbol id from the forecasts from https://api.met.no/weatherapi/weathericon/1.1/?symbol=5&content_type=image/png
});