【问题标题】:jQuery $.when Firing ImmediatelyjQuery $.when 立即触发
【发布时间】:2019-07-20 13:19:28
【问题描述】:

我正在尝试将 AJAX 调用批处理在一起,以便在它们全部完成后获得一个事件:

this.xhrs.push($.ajax({ type: "POST", url: this.options.firstUrl, data: this.options.data, datatype: 'json' }));
this.xhrs.push($.ajax({ type: "POST", url: this.options.secondUrl, data: this.options.data, datatype: 'json' }));
this.xhrs.push($.ajax({ type: "POST", url: this.options.thirdUrl, data: this.options.data, datatype: 'json' }));
this.xhrs.push($.ajax({ type: "POST", url: this.options.fourthUrl, data: this.options.data, datatype: 'json' }));

$.when
    .call($, this.xhrs)
    .done(function(first, second, third, fourth) {
        ...[process data]...

        this.loading.hide();
        this.map.fitBounds(this.bounds);
        this.map.setZoom(this.map.getZoom() - 1);
    }.bind(this));

但是该函数会立即调用,我也尝试过 .then 而不是 .done 但它也会立即触发。

绝对不是因为 AJAX 调用返回太快而无法注意到,因为其中一个调用需要 20 秒才能返回数据。

我做错了什么?

【问题讨论】:

    标签: javascript jquery ajax deferred


    【解决方案1】:

    您想使用$.when.apply() 而不是$.when.call()


    摘自Function.prototype.call() docs

    ...根本区别在于call() 接受参数列表,而apply() 接受单个参数数组。


    在您的情况下,您传入一个数组,而数组本身不是一个承诺,因此使用call() 将导致$.when 立即解决。

    使用 apply() 会将数组中的所有承诺分散到单独的参数中......每个参数都必须在 $.when 被解析之前解决


    由于现在所有现代浏览器都支持Promise API,因此您也可以这样做:

    Promise.all(this.xhrs).then(function(allResults){...`
    

    【讨论】:

    • 啊,菜鸟的错误。我不敢相信我真的事先用谷歌搜索过,以确保我使用的是正确的,我的速读显然需要改进。
    猜你喜欢
    • 2014-11-07
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    相关资源
    最近更新 更多