0

I'm working on learning OO Javascript, callbacks and closures and I'm a bit baffled by this behavior. Here is my working code, the callback works and I get the response in the console:

var XMLLoader = (function() {
    console.log("Successfully loaded 'XMLLoader.js'...");

    var xml;
    var xhr;

    return {
        setXml: function(xmlPath) {
            xml = xmlPath;
        },
        makeRequest: function(callback) {
            xhr = new XMLHttpRequest();
            xhr.onload = function() {
                callback(xhr.responseXML);
            };
            xhr.open("GET", xml);
            xhr.send(null);
        }
    };
}());

XMLLoader.setXml("xml/test.xml");
XMLLoader.makeRequest(function(e) {
    console.log(e);
});

The issue that I'm having is that I would like to store the responseXML inside the XMLLoader and return it using something like var x = XMLLoader.getXMLDoc(); Can anyone point me in the right direction on how to do this? I've tried making assignments from within the callback to no avail.

  • Because the call is asynchronous and you try to reference the value before it is called. It is like ordering a pizza and eat it as soon as you hang up the phone. It is not going to happen, you need to wait until the pizza is delivered. – epascarello Nov 14 '15 at 22:12
  • I've read that answer and all the other linked within that one. In fact, my example follows the one you linked EXACTLY and it still doesn't work. I'm just trying to figure out where I went wrong. – ewokthegreat Nov 14 '15 at 22:52
  • You are not waiting to the onComplete when you call the getXMLDocument line. Yes you are using onComplete, but your logic that needs wait until that is triggered That is what the callback/promises are for. – epascarello Nov 15 '15 at 01:13
  • Hopefully now this doesn't seem like a duplicate... – ewokthegreat Nov 15 '15 at 02:58
  • It is a dupe... You do not understand asynchronous calls. You can not make an Ajax call and than next step expect it to be returned. You need to do all the logic triggered inside of the onComplete call, not outside of it. – epascarello Nov 15 '15 at 04:37
  • Which is why I asked the question. Thanks for being so awesome. – ewokthegreat Nov 15 '15 at 04:42

0 Answers0