【问题标题】:Wait till all async call are finished [duplicate]等到所有异步调用完成[重复]
【发布时间】:2016-02-03 17:40:32
【问题描述】:

我在 for 循环中调用 jquery 异步调用:

for (var index = 0; index < activeSheets.length; index++) {
          service.getAsync().then(donecallback, failcallback);
}

当我得到 donecallback 时,根据返回的数据,我需要运行另一个 for 循环并运行更多调用,

有没有什么好简单的方法可以等到所有这些都完成,看看是全部通过还是有些失败?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

你可能正在寻找Promise.all(),它会执行所有的promise并等待它们所有通过或一个失败。

var asyncs = [];
for (var index = 0; index < activeSheets.length; index++) {
    asyncs.push(service.getAsync());
}
Promise.all(asyncs).then(donecallback, failcallback);

【讨论】:

    【解决方案2】:

    使用 jQuery 延迟 API。 https://api.jquery.com/jquery.when/

    它期望多个承诺作为参数。

    $.when(promise, promise, promise)
      .done(function success() { })
      .fail(function failure() { })
      .always(function always() { });
    

    如果所有的 Promise 都成功,它就会解决,如果其中任何一个失败,它就会失败。

    【讨论】:

    • 您不能将这种方式的 promise 数组传递给 jq $.when() 方法,它应该是例如:$.when.apply($, [promise, promise, promise])
    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 2016-03-16
    • 2011-10-04
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多