Jav*_*ier 9 javascript jquery jquery-deferred
想象一下我们想要在'foo'和'bar'的并发请求成功完成后执行某些操作的情况,或者如果其中一个或两个都失败则报告错误:
$.when($.getJSON('foo'), $.getJSON('bar'))
.then(function(foo, bar) {
console.log( 'I fire if BOTH requests are successful!' );
})
.fail(function() {
console.log( 'I fire if one or more requests failed.' );
});
Run Code Online (Sandbox Code Playgroud)
我怎样才能确定1)'foo'请求失败,或2)'bar'请求失败,或3)如果两者都失败了?
Sea*_*ira 10
只需为从$.getJSON以下位置返回的每个承诺添加一个失败调用:
function make_error_handler(msg) {
return function() { console.log(msg); };
}
$.when($.getJSON('foo').fail(make_error_handler("foo failed"))
, $.getJSON('bar').fail(make_error_handler("bar failed")))
.then(function(foo, bar) {
console.log( 'I fire if BOTH requests are successful!' );
})
.fail(function() {
console.log( 'I fire if one or more requests failed.' );
});
Run Code Online (Sandbox Code Playgroud)
如果您需要更细粒度的控件,可以重载$.getJSON以将其他信息返回到失败函数 - 请参阅jQuery的文档deferred.rejectWith