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





This worked perfectly. Thank you so much!
– Leonardo Steil
Sep 2 at 21:12



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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)