1

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?

4
  • Yes. Promise is the right way Commented Jan 17, 2017 at 7:37
  • But won't I run into the same problem? What will signal the promise was fulfilled? @Rajesh Commented Jan 17, 2017 at 7:39
  • Following is a sample JSFiddle using callbacks. You have to do similar using promise Commented Jan 17, 2017 at 7:48
  • I'm afraid changing my function from a loop to recursion could cause stack overflow, the bounds of the loop can be pretty big. @Rajesh Commented Jan 17, 2017 at 7:59

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

3 Comments

It doesn't for me, here is a fiddle: jsfiddle.net/ahrxc9gg Remember that if the asyncFunction needs 500ms to finish, the script will need ~8 minutes to work...
I meant when changing my actual function to work like this, maybe it's because the bounds are larger than 999 and the asyncFunction is heavier...
Probably, try to change it to 2 instead of 999, then you can verify wether or not it's because a memory leak of some sort or simply because it needs too much time.
1

Async library has all the functionality you need: http://caolan.github.io/async/

5 Comments

Seems like a nice library but I prefer to not add a full library just for one function...
You don't need to add the full library, you can use ES2015 import feature and only add the functionality you need: $ npm install --save async-es import {MODULE_YOU_NEED} from 'async-es/{MODULE_YOU_NEED}'; import async from 'async-es';
I need this for the client side, are you supposed to run import {MODULE_YOU_NEED}... in the console? Because it doesn't work in windows.
Is there a way to bring to the browser just the part of the library that I need? (eachSeries)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.