简体   繁体   中英

async.each calls callback not at the end

I am using the async.each function to asynchronously fire off some I/O functions and want to use the optional callback feature to continue when all functions have finished doing their thing.

However, when running the example code below, one can see that this works fine, if the iterator is a synchronous function, but it doesn't seem to work with asynchronous functions. What am I doing wrong?

This example code should work in the browser console:

 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> 

This gives me the output:

"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"

I would expect "each async func: end" to be called at the end ...

The problem was, that I was using the current master commit and not the release version of async.js. Version 1.4.0 works just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM