Reputation: 16511
I have 2 sections in my webpage that require individual AJAX calls followed by the templating of data before injecting the content into the DOM. Right now I'm looking at the best way of doing this and I've been reading a lot of articles about jQuery Deferreds, so many to the point that I'm not entirely sure what the best way is. Below is the code that I think I would use but I would really appreciate some input. I'm also super hazy about caching if anyone would like to add some advice about that.
JS
function ajaxCall1() {
var dfd = $.Deferred();
return $.ajax({
type: 'POST',
dataType: 'json',
url: '/url1',
data: { },
success: function(data) {
// Run templating code
}
});
return dfd.promise();
}
function ajaxCall2() {
var dfd = $.Deferred();
return $.ajax({
type: 'POST',
dataType: 'json',
url: '/url2',
data: { },
success: function(response) {
// Run templating code
}
});
return dfd.promise();
}
$.when( ajaxCall1(), ajaxCall2() )
.then(function(){
// Display DOM elements
})
.fail(function(){
// Display error message
});
Upvotes: 1
Views: 112
Reputation: 16584
In order to work with Deferreds you should
1 - generate a new $.Deferred()
2 - return its .promise() from the function
3 - .resolve() the deferred in the callback of the Ajax request
Something in the lines of
function ajaxCall1() {
var dfd = new $.Deferred();
$.ajax({
...
success: function(data) {
dfd.resolve(data);
}
});
return dfd.promise();
}
function ajaxCall2() {
var dfd = new $.Deferred();
$.ajax({
...
success: function(data) {
dfd.resolve(data);
}
});
return dfd.promise();
}
$.when(ajaxCall1(), ajaxCall2()).then(function(data1, data2) {
// data1 holds the result of the first ajax call, data2 that of the second call
});
EDIT: Since $.ajax() already returns a deferred, you could do it simply like
function ajaxCall1() {
return $.ajax({
...
});
}
function ajaxCall2() {
return $.ajax({
...
});
}
$.when(ajaxCall1(), ajaxCall2()).done(function(data1, data2) {
// data1 holds the result of the first ajax call, data2 that of the second call
});
Upvotes: 1