AJAX in JS Module Pattern
AJAX in JS Module Pattern
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.
1 Answer
1
Your function getFilmes()
is asynchronous and doesn't return anything. A simple solution is to add a callback parameter like this:
getFilmes()
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
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
This worked perfectly. Thank you so much!
– Leonardo Steil
Sep 2 at 21:12