0

I have been trying to save the data in stringAll but when I run Line 2(mentioned in comments), it does not show anything. For line 1, it prints the data to console. I am guessing this has got to do with the scope of the variable but I am not able to come up to a definite conclusion. Please help!!

        let stringAll = ""
  
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;

        xhr.addEventListener("readystatechange", function() {
        if(this.readyState === 4) {
            stringAll = this.responseText;
            //Line 1: console.log(stringAll); 
        }
        });

        xhr.open("GET", "https://api.covid19api.com/total/dayone/country/india/status/confirmed");

        xhr.send();

        //Line 2: console.log(stringAll)
Adi
  • 1
  • 4

1 Answers1

-1

You just need to understand how async callbacks works. Consider this article for example.

Line 2: console.log(stringAll) runs before you get readystatechange event, so console.log shows you empty string.

heleg
  • 241
  • 3
  • 12
  • What changes should I make in my code, so that I am able to assign the data to the variable? Because I want to make changes in that data in different functions – Adi May 20 '20 at 05:29
  • In this case your xhr handling code should be evaluated inside xhr callback. Just like `Line 1` does. Yes, it looks inconvenient, but this is how javascript works. There's few suggestions: http://callbackhell.com. Personally I recommend to use [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or even [async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). – heleg May 20 '20 at 05:45