lundi 27 mars 2017

How do I return data from a callback inside an XMLHttpRequest using the JavaScript Exports Module pattern?

I have this,

  var JOHNNY = (function()
    {
        var module = {};
        function getData(id, callback){
                var xhr = new XMLHttpRequest();
                var url = "http://someurl/api/5";

                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && (xhr.status == 200)) {
                        callback(xhr.response);
                    }
                };

                xhr.open("GET", url, true);
                xhr.responseType = 'json';
                xhr.send(null);

        }
        function myCallBack(data){
            return data;  //console.log works;
        }
        module.getStuff=function(id){
            return getData(5, myCallBack);  //just hardcoded id here
        }
        return module;
    })();

Data is returned. I can step through it, but as soon as I run it in the console:

JOHNNY.getStuff(5);
undefined

never get anything else (I'm in the console.) If I change the return in the callback to console.log(data), I get the data, so I know the url is good.

Due to the async nature of the call, I put a callback. But I am also trying to follow an "Exports" pattern variation of the Module pattern.

How do I get the data from the callback? I've seen lots of examples when not using the Exports variation, but nothing else. For example, this, Javascript module pattern with Ajax callback. This one was never answered, Returning data resolved by XMLHttpRequest with module pattern function and I evidently cannot understand this one, Javascript module pattern, ajax functions callbacks.

I can get the data if I do this,

function myCallBack(data){
    module.test = data;
}

and then,

JOHNNY.test;

But I don't know if that's the right way or not. Plus, how does this work when module has already been returned?

I'm not using jQuery (please no jQuery response), just straight JavaScript.

Edit: I was hoping to fix this without Promises. I do not understand why the callback does not fix the problem.

Aucun commentaire:

Enregistrer un commentaire