0

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
  });
WhoAmI
  • 1,059
  • 6
  • 15
  • 40
  • I think you're getting it right. You're probably not entirely comfortable with the asynchronous nature of Javascript, so read some guides on using promises and async/await. – TKoL Feb 18 '19 at 10:51
  • But if you want more guidance, post some example code of how you're intending to use this stuff. I'll try to give you some guidance. – TKoL Feb 18 '19 at 10:52
  • There is no right answer here. Yes you can assign data to a 'global' variable (although I'd suggest at least putting everything in a function closure) and then trigger other functions when deal with that. Or you could create a JS object (or class) which has methods to retrieve and manipulate the data. Or you could bundle the request in a promise to more readily chain that with other requests. And if you do THAT you could go down the async/await route to make your async code look more synchronous. Your choices are all, ultimately, a matter of opinion (and the web is not short of those). – Euan Smith Feb 18 '19 at 10:55
  • 2
    You can return a [promise from xhr](https://stackoverflow.com/questions/30008114/how-do-i-promisify-native-xhr) and use that value to do something after the response is finished or failed (`p.then(result=>...)` or `p.catch(error=>...)`) – HMR Feb 18 '19 at 10:55
  • @EuanSmith Thanks for the input, i am with you regarding function disclosure. I must admit i'm not very femiliar with async/await, i will look that up. – WhoAmI Feb 18 '19 at 11:22

0 Answers0