I’m sort of new to programming asynchronously. I’ve run into a situation where I need to perform 8 database lookups in a loop. I’m not sure how to accomplish this– my database library returns the data in a callback function, and I cannot continue with my code until I have all 8 rows, so I need to halt until all 8 lookups have completed.
This is sort of what I picture right now:
db.world.Queue.find(@user.kingdom.troops_queue).on 'success', (troops_queue) ->
db.world.Queue.find(@user.kingdom.tanks_queue).on 'success', (tanks_queue) ->
#etc etc
This is horrible and gross of course, but I can’t think of a way to roll it up into a loop that will allow my code to pause and only continue when the last item has been filled. I was looking into things like jQuery’s .each() function, but what is the behavior of that function? Does the code after it immediately continue, or does it wait for the loop to finish?
There are two commonly used ways. The first one is using a library like caolans async:
The second approach is streamlinejs:
However, both solutions assume that the first argument of the callback is the error – if it isn’t that way, you should bug the author of the library you’re using to change it.