jQuery什么时候,中止多个Ajax

如果有多个Ajax调用的延迟对象的jQuery被停止 (中止),那么任何挂起的Ajax调用都不会被调用?

示例代码(最小):

var deferred = $.when( $.getJSON( "a.json" ), $.getJSON( "b.json" ) ) .done(( res )=>{ // whatever... }); // abort the all AJAX calls after N miliseconds setTimeout(()=>{ deferred.abort() }, 2000); 

但是,当然,不能简单地执行deferred.abort()因为abort方法不存在。

这不是你从$.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); 

或者实际上,更一般地说,只是一个with -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); 

我最终做了:

 var ajaxCalls = [ $.getJSON( "a.json" ), $.getJSON( "b.json" ) ]; $.when(...ajaxCalls) .done(( res )=>{ // whatever... }); // abort the all AJAX calls after N miliseconds setTimeout(()=>{ ajaxCalls.forEach(a => a.abort()) }, 2000); 

太糟糕了, when方法结果不会公开提供给它的参数列表,因此可以直接访问(在这种情况下中止)。