I've got a problem where I've got three Ajax calls I need to make to retrieve some strings. If any of them fail, I need to use a default string instead. I want my page to wait until all the strings have been resolved (or rejected) before moving on.
What I have so far looks something like this:
var myObj = {
initialize: function(){
// Start fetching this stuff right away
var that = this;
this.promise1 = $.ajax(url: 'url1').then(function(result){
that.string1 = result
).fail(function(){
that.string1 = 'string1Default';
});
this.promise2 = $.ajax(url: 'url2').then(function(result){
that.string2 = result
).fail(function(){
that.string2 = 'string2Default';
});
this.promise3 = $.ajax(url: 'url3').then(function(result){
that.string3 = result
).fail(function(){
that.string3 = 'string3Default';
});
}
getStrings: function(){
return {
string1: this.string1,
string2: this.string2,
string3: this.string3
};
}
doThingWithStrings: function(callback){
var that = this;
return $.when(this.promise1, this.promise2, this.promise3)
.always(function(){callback(that.getStrings())})
}
}
myObj.initialize(); // start fetching
// ... do some other stuff
myObj.doThingWithStrings(loadThePageWithStrings);
There are two problems with this. One is that it just feels harder than it should be.
The second more important problem is that $.when executes .done() when all have been resolved, but .fail() as soon as any have been rejected. What I really need is something that executes after all promises have are no longer pending, whether they resolved successfully or were rejected. $.when seems to be almost, but not quite, what I want. I don't want to show the page until I've retrieved (or failed to retrieve) each of the three strings. How can I do this?