gpt4 book ai didi

javascript - jQuery when/then/fail with concurrent ajax requests : Which request failed?

转载 作者:数据小太阳 更新时间:2023-10-29 03:50:12 32 4
gpt4 key购买 nike

想象这样一种场景,我们想要在对“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.' );
});

我如何确定 1) 对“foo”的请求是否失败,或者 2) 对“bar”的请求是否失败,或者 3) 如果两者都失败了?

最佳答案

只需为从 $.getJSON 返回的每个 promise 添加一个失败调用:

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.' );
});

如果您需要更细粒度的控制,您可以重载 $.getJSON 以将附加信息返回给 fail 函数——参见 jQuery 文档 deferred.rejectWith

关于javascript - jQuery when/then/fail with concurrent ajax requests : Which request failed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5794964/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com