简体   繁体   中英

Using async function inside a loop and calling a callback only after the loop has finished

I'm trying to write a function that calls an async function in a loop, and only when the loop has finished, to call the callback with the result.

Something like this:

function foo(cb){
    var result;
    for(var i=0; i < 999; i++){
        asyncFunction(i, function(val){
            do something with result
        });
    }
    cb(result);
}

But I see that it gets to cb(result); before it actually finishes returning from all the asyncFunction calls.

What can be done to make it wait to finish the loop before calling cb ? Will a promise help?

异步库具有您需要的所有功能: http : //caolan.github.io/async/

Maybe this helps you more:

function asyncFunction (callback) {
  // Do stuff
  return callback()
}

function foo () {
  var result = 0
  for (var i = 0; i < 999;) {
    asyncFunction(function () {
      i++
      result += i
    })
  }
  console.log(result)
}

foo()

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