1
我們都熟悉the $.Deferred()
behaviour當它成功和失敗:遞延當返回備份失敗
function foo() {
var backup = 'bar',
dfd = $.ajax(...)
.done(function(data, textStatus, jqXHR) {
alert(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
});
return dfd.promise();
}
// outside the function
$.when(foo())
.always(function(something) {
// 'something' is either data, OR jqXHR, depending if the thing fails
});
不過,我的data
,被稱爲backup
備份結果,居住功能foo
裏面,那我d希望在請求失敗時返回。
只要我能在$.ajax(...)
設置爲既不改變參數(這意味着我不能添加一個「失敗」的處理程序),也無法改變的foo
返回類型,也不是外foo
移動backup
,我怎麼能達到以下效果?
function foo() {
var backup = 'bar',
dfd = $.ajax(...)
.done(function(data, textStatus, jqXHR) {
alert(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
// replace return with 'bar', which is impossible
// because 'data' is undefined
data = backup;
});
return dfd.promise();
}
// outside the function
$.when(foo())
.always(function(something) {
// 'something' is now some fresh data, or 'bar' if ajax fails
});
就像一個魅力。謝謝你的提示! – Brian