在传递多个AJAX调用时,我不理解$.when
在失败期间的工作原理。如果一个失败,失败回调会触发吗?另外,失败的参数是什么,每个ajax一个,还是一个失败共享?
$.when(
$.ajax('/url1'),
$.ajax('/url2'))
.done(function (resp1, resp2) {
}).fail(function (??) {
});
答案 0 :(得分:4)
这应该很容易检查吗?
var d1 = $.Deferred(), d2 = $.Deferred();
$.when(d1, d2)
.fail(function (a, b) {
console.log(a, b);
});
d2.reject("hi!");
输出为hi! undefined
。所以只传递了一个参数。
答案 1 :(得分:1)
.then()
实际上最多需要三个参数(成功,失败,进度)。您可以使用其他答案中提到的.fail()
,也可以执行以下操作:
$.when(async).then(function success(resp) {
console.log('success');
}, function fail(resp) {
console.log('fail');
});
答案 2 :(得分:0)
当任何承诺被拒绝时,将调用最终的失败。 如果你想为每个人做一些不同的事情,你可以尝试这样的事情:
$.when(
$.ajax('/url1').fail(function () { console.dir('fail 1'); }),
$.ajax('/url2').fail(function () { console.dir('fail 2'); }))
.done(function (resp1, resp2) {
}).fail(function () {
console.dir('fail any');
});
在其中一个ajax请求失败后立即调用任何失败,因此之后可能会调用其他特定于请求的失败。
答案 3 :(得分:0)
我正在做类似的事情,并认为它可能对某人有所帮助。
A CodePen playground with $.when
var d1 = $.Deferred().fail(function(a){ console.log('on fail 1', a) }),
d2 = $.Deferred().fail(function(a){ console.log('on fail 2', a) }),
d3 = $.Deferred().fail(function(a){ console.log('on fail 3', a) });
$.when(d1, d2, d3)
.then(function (a, b, c){
console.log('then: ', a, b, c);
})
.fail(function (a, b, c) {
// only reports the first one that failed
console.log('fail: ', a, b, c);
})
.always(function(a, b, c){
console.log('always: ', a, b, c);
});
d1.resolve("d1!");
d2.reject("d2!");
d3.reject("d3!");
A way to 'recover' from 1 failed in the array of deferreds
'use strict';
var getConfigRequestDef = $.Deferred();
var getConfigDef = $.Deferred();
var getStatusRequestDef = $.Deferred();
var getStatusDef = $.Deferred();
getConfigRequestDef.then(function (cfg) {
return getConfigDef.resolve(cfg);
}, function (c) {
c.hasError = true;
getConfigDef.resolve(c);
});
getStatusRequestDef.then(function (status) {
return getStatusDef.resolve(status);
}, function (s) {
s.hasError = true;
getStatusDef.resolve(s);
});
var results = $.when(getConfigDef, getStatusDef).then(function (config, status) {
console.log('The when\'s then: ', JSON.stringify(config), JSON.stringify(status));
});
var cfg = {
id: 10,
type: 'config',
hasError: false
};
var statusObj = {
id: 30,
type: 'status',
hasError: false
};
getConfigRequestDef.reject(cfg);
getStatusRequestDef.reject(statusObj);