How to deal with closures?

Not completely sure that’s related to closures…but my problem is the following.
I’ve got this function:

function loadXMLDoc() {
            var xmlhttp = new XMLHttpRequest();
			xmlhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) 
                    XMLParser(this);
					
            };
			xmlhttp.open("GET", "running.xml", true);
            xmlhttp.send();
        }

I want the value returned from XMLParser() function to be available outside the loadXMLDoc() function. I tried in any possible way without success…at this point, I’ve started doubting that’s not even possible to do while handling an XMLHttpRequest.

Can anybody give me some help with it and, maybe, redirect me to some in depth source about this issue? Just not to fall again in this mistake because, as I said, I’m not completely sure that’s related to closures.

Depending on your user case/functionality you can simply assign the returned string into a variable accessing outside of the function scope, or call a method with that return:

let outsideVar = "";

function loadXMLDoc() {
            var xmlhttp = new XMLHttpRequest();
			xmlhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) 
                   // assign the return to the outside variable
                   outsideVar =  XMLParser(this);
		 // or call a method from here
                 const parserReturn = XMLParser(this);
                 myMethod(parserReturn)
            };
// ...
   }

Haven’t used XML in a very long time tho, so I might be wrong.
Hope it helps :slight_smile:

p.s. a reproducible demo would greatly help

I agree with Marmiz.

It sounds like a pretty standard issue of dealing with asynchronous functions, the same with any AJAX request. It is one of the peculiarities of JavaScript but a very important concept to understand for the language. I’d do some searching on youtube for “asynchronous javascript”. It’s a hard concept to wrap your head around and will drive you crazy in the beginning but is one of the most powerful features of JavaScript once you master it.