繁体   English   中英

jQuery $ .when立即射击

[英]jQuery $.when Firing Immediately

我正在尝试将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秒才能返回数据。

我究竟做错了什么?

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


摘自Function.prototype.call() docs

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


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

使用apply()会将数组中的所有promise散布到各个参数中...每个参数都必须在$.when解析之前解析


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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM