Reputation: 1423
I'm new to the module pattern and closures in javascript. I'm trying to create a module that gets JSON data so I can display it on my webpage.
var EmailLogs = (function(){
var emailLogs = [];
var config = {};
function init(options){
for(var prop in options) {
if(options.hasOwnProperty(prop)){
config[prop] = options[prop];
}
}
setEmailLogs();
}
function setEmailLogs(){
$.ajax({
type: "POST",
headers : { "cache-control": "no-cache" },
url: "../../ajax/adminGetEmailLogs.php",
data: {options: JSON.stringify(config)},
dataType: 'json',
success: function(values){
if(values.success)
{
emailLogs = values.emailLogs;
}
}
});
}
function getEmailLogs(){
return emailLogs;
}
return{
init: init,
getEmailLogs: getEmailLogs,
}
})();
var options = {
sData : [
'email_id'
],
filters : {
user_id : 44860,
}
}
EmailLogs.init(options);
console.log(EmailLogs.getEmailLogs());
I'm trying to run the ajax call when init is run. Then I'm looking to get the emailLogs variable to display. I presume because my ajax is being run async, that's why I can't get my variables after. How do I make sure setEmailLogs() has ran before I running getEmailLogs().
Upvotes: 0
Views: 63
Reputation: 979
$.ajax()
implements the Promise interface and will return a Deferred object, see the jQuery docs
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).
This means that you can use the promise interface to make sure the desired method is run after $.ajax()
is done.
Modify your code to something make use of the promise interface. Basically $.ajax()
returns to you the promise that it will be executed. You can then chain your next method to execute once the promise is satisfied. You often see patterns like this chaining multiple promises (in psuedo code):
doAjaxRequest()
.then(doSomethingElse)
.then(doAnotherSomethingElse)
This way you can write quite clean async code as oppossed to haven a lot of callbacks invoking eachother.
The documentation for Q promises has some good examples that explain the way promises work.
I modified your snippet to uses promises:
var EmailLogs = (function(){
var emailLogs = [];
var config = {};
function init(options){
for(var prop in options) {
if(options.hasOwnProperty(prop)){
config[prop] = options[prop];
}
}
setEmailLogs().done(function(values) {
if(values.success)
{
console.log(values.emailLogs)
}
});
}
function setEmailLogs(){
return $.ajax({
type: "POST",
headers : { "cache-control": "no-cache" },
url: "../../ajax/adminGetEmailLogs.php",
data: {options: JSON.stringify(config)},
dataType: 'json'
});
}
return{
init: init,
getEmailLogs: getEmailLogs,
}
})();
var options = {
sData : [
'email_id'
],
filters : {
user_id : 44860,
}
}
EmailLogs.init(options);
Upvotes: 1