vsy*_*ync 2 javascript ajax jquery promise
如果有多个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);
Run Code Online (Sandbox Code Playgroud)
但是,当然,deferred.abort()由于该abort方法不存在,所以不能简单地做到.
这不是您回来的承诺的一个特征$.when.不过你可以自己写一下:(尽管如此,请参阅下面的替代方案.)
function whenWithAbort(...xhrs) {
return {
abort() {
xhrs.forEach(xhr => {
xhr.abort();
});
},
promise: $.when(...xhrs)
};
}
Run Code Online (Sandbox Code Playgroud)
用法:
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);
Run Code Online (Sandbox Code Playgroud)
或者实际上,更一般地说,只是一个when带数组:
function whenPlus(...list) {
return {
list,
promise: $.when(...list)
};
}
Run Code Online (Sandbox Code Playgroud)
然后:
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);
Run Code Online (Sandbox Code Playgroud)
或者你可以给它一个方法来调用所有条目的命名方法:
function whenPlus(...list) {
return {
list,
callOnEach(method) {
list.forEach(entry => { entry[method]() });
},
promise: $.when(...list)
};
}
Run Code Online (Sandbox Code Playgroud)
然后:
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);
Run Code Online (Sandbox Code Playgroud)