I'm creating an application using Module Pattern in JS. I've create two modules and I have this code:
var dataController = (function () {
var request = new XMLHttpRequest();
var getFilmes = function () {
request.onreadystatechange = function() {
if(request.readyState === 4) {
if(request.status === 200) {
var obj = JSON.parse(request.responseText);
return obj;
} else {
console.log('An error occurred during your request: ' + request.status + ' ' + request.statusText);
}
}
}
request.open('Get', 'http://localhost:8080/api/filmes/5b8947446f506266bc522f38');
request.send();
}
return {
filmes: function (){
return getFilmes();
}
};
})();
var controller = (function (dataCtrl) {
var preencheFilmes = function(){
var obj = dataCtrl.filmes();
console.log(obj);
}
return {
init: function(){
console.log("APP START");
preencheFilmes();
}
};
})(dataController, UIController);
controller.init();
The problem is that I can't get the response from AJAX when I'm calling preencheFIlmes in the "init". But I can get the result in the dataController.
Someone can help me? I'm learning how to work with this pattern.
Thank you so much.
Your function getFilmes()
is asynchronous and doesn't return anything. A simple solution is to add a callback parameter like this:
var getFilmes = function(callback) {
request.onreadystatechange = function() {
if(request.readyState === 4) {
if(request.status === 200) {
var obj = JSON.parse(request.responseText);
callback(obj); // <-- calls the callback function
} else {
...
}
}
}
...
}
Then you can pass an anonymous callback function when you want to get the results:
var preencheFilmes = function(){
dataCtrl.filmes(function(obj) {
console.log(obj);
});
}
Another option is to use the async/await feature, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function