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

怎甘沉沦 提交于 2019-12-24 23:19:51

问题


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.

来源:https://stackoverflow.com/questions/43056951/how-do-i-return-data-from-a-callback-inside-an-xmlhttprequest-using-the-javascri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!