jQuery $.when 立即触发



我正在尝试将 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()文档:

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


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

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


由于现在所有现代浏览器都支持Promise API,因此您也可以执行以下操作:

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

最新更新