Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I perform many asynchronous database requests without deeply nesting my code?

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?

like image 541
Nicholas Flynt Avatar asked Mar 21 '26 14:03

Nicholas Flynt


1 Answers

There are two commonly used ways. The first one is using a library like caolans async:

async.parallel
  a: (cb) -> doTaskA cb
  b: (cb) -> doTaskB cb
, (err, {a, b}) ->
  # you can use err, a and b here now

The second approach is streamlinejs:

troops_queue = db.world.Queue.find(@user.kingdom.troops_queue).on 'success', _
tanks_queue = db.world.Queue.find(@user.kingdom.tanks_queue).on 'success', _
# go on here

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.

like image 171
thejh Avatar answered Mar 23 '26 02:03

thejh