这不是您从$.when 得到的承诺的功能。不过,您可以轻松地自己编写它:(不过,请参阅下面的替代方法。)
function whenWithAbort(...xhrs) {
return {
abort() {
xhrs.forEach(xhr => {
xhr.abort();
});
},
promise: $.when(...xhrs)
};
}
用法:
var ops = whenWithAbort(
$.getJSON( "a.json" ),
$.getJSON( "b.json" )
)
.promise.done(( res )=>{
// whatever...
});
// abort the all AJAX calls after N miliseconds
setTimeout(()=>{ ops.abort() }, 2000);
或者实际上,更一般地说,只是一个when-with-array:
function whenPlus(...list) {
return {
list,
promise: $.when(...list)
};
}
然后:
var ops = whenWithAbort(
$.getJSON( "a.json" ),
$.getJSON( "b.json" )
)
.promise.done(( res )=>{
// whatever...
});
// abort the all AJAX calls after N miliseconds
setTimeout(()=>{ ops.list.forEach(op => { op.abort() } }, 2000);
或者你可以给它一个在所有条目上调用命名方法的方法:
function whenPlus(...list) {
return {
list,
callOnEach(method) {
list.forEach(entry => { entry[method]() });
},
promise: $.when(...list)
};
}
然后:
var ops = whenWithAbort(
$.getJSON( "a.json" ),
$.getJSON( "b.json" )
)
.promise.done(( res )=>{
// whatever...
});
// abort the all AJAX calls after N miliseconds
setTimeout(()=>{ ops.callOnEach("abort") }, 2000);