jQuery什么时候,中止多个Ajax [英] jQuery When, abort multiple Ajax

查看:55
本文介绍了jQuery什么时候,中止多个Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有多个Ajax调用的jQuery 何时延迟对象如何停止(已中止),因此不会调用任何挂起的Ajax调用?

How can a jQuery when deferred object which has multiple Ajax calls be stopped (aborted), so any pending Ajax calls will not be called?

示例代码(最小):

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 方法不存在。

But of course, one cannot simply do deferred.abort() since the abort method does not exist.

推荐答案

这不是你从 $。返回的承诺的一个特征。不过你可以自己写一下:(尽管如此,请参阅下面的内容。)

This isn't a feature of the promise you get back from $.when. You can readily write it yourself, though: (See below for an alternative, though.)

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-array:


Or actually, more generically, just a 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);

或者你可以给它一个方法来调用所有条目的命名方法:

Or you could give it a method that calls a named method on all entries:

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);

这篇关于jQuery什么时候,中止多个Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆