FAC6/facfaq

Running a callback after forEach

Closed this issue · 8 comments

How do you run a callback which waits for a forEach function to finish before it is called?

@hdrdavies forEach is sync. see: http://ecma262-5.com/ELS5_HTML.htm#Section_15.4.4.18
which means you can put your callback on the next line after it has run.
(unless you are running a bunch of async calls inside the forEach block...?)

@iteles Yes you're right - we did see that here too:

http://stackoverflow.com/questions/18983138/callback-after-foreach-is-done

But we're trying to populate an array above the forEach function (using arr.push() inside the forEach), and then create a object using that array (after the forEach function). The object is created before the forEach is finished, with an empty array which hasn't been populated by the push method yet- so it doesn't work, hence why we felt the need for a callback......

Is your code on GitHub?

yep! Here! As you can see, the problem is currently being solved with a setTimeout function here.

Solved! As usual, I should have just asked @des-des 😆

@hdrdavies when posting links to code, please add commit hash so that the link is preserved when you update the code... (makes this question useful to others...)

@hdrdavies FYI If you're in a file, just press the 'Y' key and it'll insert e current commit ID into the URL

@iteles Thanks for the top tip! @nelsonic quite right, my problem was that I was locating the clusterer here when I should have been doing it here, within the callback but after the forEach. Forgive the messy code, it's since been cleaned up!