【问题标题】:Resolve promises from a loop with jQuery [duplicate]使用 jQuery 解决循环中的承诺 [重复]
【发布时间】:2017-02-21 03:41:05
【问题描述】:

所以一个 XHR 在一个循环中运行,我想在所有 XHR 完成后执行一个函数,我尝试了如下承诺。

var promises = [];
for(var i=0;i<5;i++){
    promise = $.ajax({
                    type: "POST",
                    url : data_url,
                    data:pdata
    });
    promises.push(promise);
}
$.when(promises).then(function(){
                window.location.href = '/cart?edit_order=true'
})

问题是重定向发生在 AJAX 完成之前,我错过了什么?

【问题讨论】:

  • 我看到您在标题中指定了 jQuery,但仅出于历史目的,您可以以“更好”的方式执行此操作,更好是指更好的可读性和可扩展性。 q.all([loadSomething(), loadAnotherThing()]) .spread(function(something, another) { DoSomethingOnThem(something, another); }); 其中loadSomething(), loadAnotherThing() 是两个承诺,q.all 来自以下承诺库:github.com/kriskowal/q

标签: javascript jquery promise


【解决方案1】:

如果我没记错的话,jQuery 的 .when() 方法不接受 Array 的承诺作为参数,而是接受单个参数。这只是意味着您需要将调用它的方式更改为:

$.when.apply( null, promises ).then(function(){
            window.location.href = '/cart?edit_order=true'
})

使用Function.prototype.apply 将自动获取一个Array 并将该Array 的每个值作为单个参数放入被调用的函数中,在本例中为.when()。有效地传播论点。

您还可以做一些 EMCAscript 魔术并为此创建一个小部分应用程序:

var when = Function.prototype.apply.bind( $.when, null );

..然后只需调用

when( promises ).then(function() { ...

【讨论】:

  • 你的意思是应用,它传播论点?
  • 在最新版本的ES中也可以使用$.when(..promises)
  • 当然,但是您“可以”也使用本机 Promise 和箭头函数等等,但是您应该强烈建议使用预编译器或转译器。目前浏览器版本还没有广泛支持解构。
  • 是的,转译可能很复杂......但关键是它是一种非常优雅的方式。 “最近的版本”是您刚才所说的建议。
猜你喜欢
  • 2020-04-09
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-22
  • 2018-07-29
  • 1970-01-01
  • 2017-09-27
相关资源
最近更新 更多