【发布时间】:2015-08-05 10:56:52
【问题描述】:
我遇到了一个问题,我需要进行三个 Ajax 调用来检索一些字符串。如果其中任何一个失败,我需要使用默认字符串。我希望我的页面等到所有字符串都已解决(或拒绝)后再继续。
到目前为止,我所拥有的看起来像这样:
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);
这有两个问题。一是感觉比应该的要难。
第二个更重要的问题是 $.when 在所有问题都解决后执行 .done() ,但在任何问题都被拒绝时执行 .fail() 。我真正需要的是在所有承诺不再待处理之后执行的东西,无论它们是成功解决还是被拒绝。 $.when 似乎几乎,但不完全是我想要的。在我检索(或检索失败)三个字符串中的每一个之前,我不想显示该页面。我该怎么做?
【问题讨论】:
-
经过更多研究(我保证,我在写这篇文章之前看过!)我想这可能是this的副本