0

I understand the var city is not getting defined by debugging it. First time execution Second time execution Actual code :

var request = new XMLHttpRequest()
request.open('GET', 'https://restcountries.eu/rest/v2/all', true)
var city;
request.onload = function() {
  var data = JSON.parse(this.response);
  var findName = data.find((item) => {
    return item.name.toUpperCase() == 'INDIA';
  })
  city = findName.capital;
}
request.send();
var request = new XMLHttpRequest();
link = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&apikey=" + "bb0a5a97e99ae93b148d219df2f4e97f";
request.open('GET', link, true);
request.onload = function() {
  var obj = JSON.parse(this.response);
  if (request.status >= 200 && request.status < 400) {
    var temp = obj.main.temp;
    console.log(temp)
  } else {
    console.log("The city doesn't exist! Kindly check");
  }
};
request.send();

can you please change the code so , it works everytime

VLAZ
  • 26,331
  • 9
  • 49
  • 67
AjithKumar
  • 21
  • 6
  • 1
    It's good that you've seen that `city` is still `undefined` when constructing the `link`, but did you understand *why* that is? – Bergi Apr 25 '20 at 16:36
  • Hi bergi, as it executes asynchronously, but i don't know how to fix. please help here. – AjithKumar Apr 25 '20 at 16:39
  • Put the code of the second request inside the `onload` callback of the first request (after the `city` assignment). Or, given that this is tagged `async`/`await`, promisify the requests, put everything in an `async` function, and await the responses. – Bergi Apr 25 '20 at 16:46

0 Answers0