99

我的代码在 javascript 中看起来像这样:

forloop {
    //async call, returns an array to its callback
}

在所有这些异步调用完成后,我想计算所有数组的最小值。

我怎么能等到他们所有人?

我现在唯一的想法是有一个名为 done 的布尔数组,并在第 i 个回调函数中将 done[i] 设置为 true,然后说 while(not all are done) {}

编辑:我想一个可能但丑陋的解决方案是在每个回调中编辑 done 数组,然后在每个回调中设置所有其他 done 时调用一个方法,因此最后一个完成的回调将调用 continue 方法。

提前致谢。

4

7 回答 7

196

你的代码不是很具体,所以我会编一个场景。假设您有 10 个 ajax 调用,并且您想累积这 10 个 ajax 调用的结果,然后当它们全部完成时,您想做一些事情。您可以通过在数组中累积数据并跟踪最后一个完成的时间来做到这一点:

手动计数器

var ajaxCallsRemaining = 10;
var returnedData = [];

for (var i = 0; i < 10; i++) {
    doAjax(whatever, function(response) {
        // success handler from the ajax call

        // save response
        returnedData.push(response);

        // see if we're done with the last ajax call
        --ajaxCallsRemaining;
        if (ajaxCallsRemaining <= 0) {
            // all data is here now
            // look through the returnedData and do whatever processing 
            // you want on it right here
        }
    });
}

注意:错误处理在这里很重要(未显示,因为它特定于您如何进行 ajax 调用)。您将需要考虑如何处理一个 ajax 调用从未完成的情况,无论是错误还是长时间卡住或长时间后超时。


jQuery 承诺

添加到我在 2014 年的回答中。如今,promise 经常用于解决此类问题,因为 jQuery$.ajax()已经返回了一个 Promise,并且$.when()会在一组 Promise 全部解决时通知您,并为您收集返回结果:

var promises = [];
for (var i = 0; i < 10; i++) {
    promises.push($.ajax(...));
}
$.when.apply($, promises).then(function() {
    // returned data is in arguments[0][0], arguments[1][0], ... arguments[9][0]
    // you can process it here
}, function() {
    // error occurred
});

ES6 标准承诺

如 kba 的回答中所述:如果您有一个内置原生 Promise 的环境(现代浏览器或 node.js 或使用 babeljs transpile 或使用 Promise polyfill),那么您可以使用 ES6 指定的 Promise。有关浏览器支持,请参阅此表。除了 IE,几乎所有当前的浏览器都支持 Promise。

如果doAjax()返回一个承诺,那么你可以这样做:

var promises = [];
for (var i = 0; i < 10; i++) {
    promises.push(doAjax(...));
}
Promise.all(promises).then(function() {
    // returned data is in arguments[0], arguments[1], ... arguments[n]
    // you can process it here
}, function(err) {
    // error occurred
});

如果你需要将一个非承诺异步操作变成一个返回承诺的操作,你可以像这样“承诺”它:

function doAjax(...) {
    return new Promise(function(resolve, reject) {
        someAsyncOperation(..., function(err, result) {
            if (err) return reject(err);
            resolve(result);
        });
    });
}

然后,使用上面的模式:

var promises = [];
for (var i = 0; i < 10; i++) {
    promises.push(doAjax(...));
}
Promise.all(promises).then(function() {
    // returned data is in arguments[0], arguments[1], ... arguments[n]
    // you can process it here
}, function(err) {
    // error occurred
});

蓝鸟承诺

如果您使用功能更丰富的库,例如Bluebird Promise 库,那么它内置了一些额外的功能来使这更容易:

 var doAjax = Promise.promisify(someAsync);
 var someData = [...]
 Promise.map(someData, doAjax).then(function(results) {
     // all ajax results here
 }, function(err) {
     // some error here
 });
于 2012-04-04T02:19:21.833 回答
18

从 2015 年开始检查:我们现在在最新的浏览器(Edge 12、Firefox 40、Chrome 43、Safari 8、Opera 32 和 Android 浏览器 4.4.4 和 iOS Safari 8.4,但不包括 Internet Explorer、Opera Mini 和旧版本)中具有原生承诺安卓)。

如果我们想要执行 10 个异步操作并在它们全部完成时收到通知,我们可以使用 native Promise.all,而无需任何外部库:

function asyncAction(i) {
    return new Promise(function(resolve, reject) {
        var result = calculateResult();
        if (result.hasError()) {
            return reject(result.error);
        }
        return resolve(result);
    });
}

var promises = [];
for (var i=0; i < 10; i++) {
    promises.push(asyncAction(i));
}

Promise.all(promises).then(function AcceptHandler(results) {
    handleResults(results),
}, function ErrorHandler(error) {
    handleError(error);
});
于 2015-11-19T20:29:37.633 回答
10

您可以将 jQuery 的Deferred对象与when方法一起使用。

deferredArray = [];
forloop {
    deferred = new $.Deferred();
    ajaxCall(function() {
      deferred.resolve();
    }
    deferredArray.push(deferred);
}

$.when(deferredArray, function() {
  //this code is called after all the ajax calls are done
});
于 2012-04-04T02:19:17.467 回答
9

您可以像这样模拟它:

  countDownLatch = {
     count: 0,
     check: function() {
         this.count--;
         if (this.count == 0) this.calculate();
     },
     calculate: function() {...}
  };

然后每个异步调用都会这样做:

countDownLatch.count++;

而在方法末尾的每个异步回调中,您添加以下行:

countDownLatch.check();

换句话说,您模拟了倒计时锁存功能。

于 2012-04-04T02:21:13.483 回答
6

这是我认为最简洁的方式。

承诺.all

FetchAPI

(由于某种原因 Array.map 在 .then 中对我不起作用。但您可以使用 .forEach 和 [].concat() 或类似的东西)

Promise.all([
  fetch('/user/4'),
  fetch('/user/5'),
  fetch('/user/6'),
  fetch('/user/7'),
  fetch('/user/8')
]).then(responses => {
  return responses.map(response => {response.json()})
}).then((values) => {
  console.log(values);
})
于 2016-04-14T19:30:39.317 回答
1

使用控制流库,如after

after.map(array, function (value, done) {
    // do something async
    setTimeout(function () {
        // do something with the value
        done(null, value * 2)
    }, 10)
}, function (err, mappedArray) {
    // all done, continue here
    console.log(mappedArray)
})
于 2012-04-04T02:28:26.027 回答
0

在 Node.js 中,您可以使用 async/await 来控制异步流程

  • Node.js 7.6 支持异步/等待
  • Node.js v8 支持 util 函数来承诺回调

示例代码:

const foo = async () => {
  try {
    const ids = [100, 101, 102];
    const fetchFromExternalApi = util.promisify(fetchFromExternalApiCallback);
    const promises = ids.map((id) => fetchFromExternalApi(id));
    const dataList = await Promise.resolve(promises); // dataList is an array
    return dataList;
  } catch (err) {
    // error handling
  }
};
于 2021-08-11T04:44:35.673 回答