How to return data from a callback inside XMLHttpRequest using JavaScript exporter template?
I have it,
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 walk through it, but as soon as I run it in the console:
JOHNNY.getStuff(5);
undefined
never get anything (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 asynchronous nature of the call, I put in a callback. But I also try to follow the "Export" pattern of the module template.
How do I get the data from the callback? I've seen many examples where I haven't used the Exports option , but nothing else. For example, this is a Javascript module template with an Ajax callback . This answer has never been answered, Returned data resolved by XMLHttpRequest with a module template function and I obviously can't figure this one out, Javascript module template, ajax is calling callbacks .
I can get data if I do this,
function myCallBack(data){
module.test = data;
}
and then
JOHNNY.test;
But I don't know if it's right or wrong. Also, how does this work when the module has already been checked back?
I am not using jQuery (please do not respond to jQuery), just straight JavaScript.
Edit: I was hoping to fix this without Promises. I don't understand why the callback doesn't fix the problem.
source to share
No one has answered this question yet
See similar questions:
or similar: