Possible duplicate:
javascript: execute a bunch of asynchronous method with one callback
I have been struggling with this problem for several days, but I just can't find an elegant way to handle this. Here is the problem.
I am running a forEach loop and I need to know when everything is complete. Since the forEach loops are locked, it should be simple enough to just leave console.log after the forEach loop, which will work when the forEach loop is complete. However, if there is any function inside the forEach loop that is not synchronized, this whole system breaks up very quickly, and I do not know when the contents of the loop will be completed, except for very strange hacker counts and if statements. My question is is there an elegant way to handle this situation in javascript.
Here are some examples:
In this case, the forEach loop works fine because everything in the loop is synchronized.
[1,2,3].forEach(function(num){ console.log("we're on " + num); }); console.log('done counting!')
Here we begin to run into problems, but as a basic example:
[1,2,3].forEach(function(num){ setTimeout(function(){ console.log(num) }, 200); }); console.log('done counting!');
Although it makes sense that this happens, I now have an unsuccessful problem on my hands that I need a callback when we have finished counting, and there is no smooth way for me to have something other than something like this
var counter = 0; var numbers = [1,2,3] var log_number = function(num){ console.log("we're on " + num); counter++; if (counter == numbers.length) { console.log("done counting!") } } numbers.forEach(function(num){ setTimeout(log_number(num), 200); });
Kindness is an awful lot of overhead. Is there a smoother way to do this? I checked the promises, pending and sequences, but I could not implement any of them in such a way as to make it more concise :(
To be clear, this is not setTimeout, in particular, this is my problem, it usually has async functions running inside the synchronization function - it was just the simplest example.