async.each不在最后调用回调

时间:2015-07-27 18:34:21

标签: javascript asynchronous async.js

我正在使用async.each函数异步触发某些I / O函数,并希望在所有函数完成它们的操作时继续使用可选的回调函数。

但是,当运行下面的示例代码时,如果迭代器是同步函数,可以看到这很好用,但它似乎不能用于异步函数。我做错了什么?

此示例代码应在浏览器控制台中运行:



function load (url, callback) {
  var request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.responseType = 'text';
  request.onload = callback;
  request.send();
}

// use async.each with an async function
async.each([1,2,3,4], function iterator(item, callback) {
    load("/", function onload() {
      console.log("inside async func: " + item.toString());
      callback();
    });
  }, function eachFinished(err) {
  console.log("each async func: end");
});

// use async.each with a sync function
async.each([1,2,3,4] , function iterator(item, callback){
  console.log("inside sync func: " + item.toString());
  callback();
  }, function eachFinished(err) {
    console.log("each sync func: end");
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/async/1.4.0/async.js"></script>
&#13;
&#13;
&#13;

这给了我输出:

"inside sync func: 1"
"inside sync func: 2"
"inside sync func: 3"
"inside sync func: 4"
"each sync func: end"
"inside async func: 1"
"each async func: end"
"inside async func: 2"
"inside async func: 3"
"inside async func: 4"

我希望最后能够调用"each async func: end" ......

1 个答案:

答案 0 :(得分:0)

问题是,我使用的是当前的主提交,而不是async.js的发布版本。版本1.4.0工作得很好。

相关问题