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