0

I am trying to find a way to ensure my database query is ran as part of the for loop shown below. I don't know if async.series is the best way, or if fibers might work? Rather than paste loads of code, in pseudo code it looks like this:

for length of array
  newArray = array.split
     databaseQuery(select **** from *** where x = newArray[0] and y = newArray[1]

my problem is as node is asynchronous, it simply repeats the for loop split while the query is running and then gets the result of the query, meaning I only get the last result returned.

Is there a way to ensure the database query is executed each time in the for loop? I've used nested queries, and callbacks in the past but I can't seem to figure out the best way to call the query each time for the loop

  • Do you need the query[n] to complete before query[n+1] or could you just run them all at once provided you collect the results? – barry-johnson Apr 01 '14 at 20:21
  • I need them to be in order. The first array is results from a query and its those results I'm using for the loop. – user3283988 Apr 01 '14 at 20:35
  • Got it. Personally I would use promises over async. I have a fairly elaborate example I provided in [this answer](http://stackoverflow.com/questions/22109487/nodejs-mysql-dump/22110015#22110015) which does something similar (needed to get a list of tables and then get create table stmts for each table). I provide an example using plain callbacks as well as an example using promises. The promises version is heavily commented. See if that might be helpful to your endeavors. – barry-johnson Apr 01 '14 at 21:10
  • Thanks Barry, looks like it has a fair amount of reading but I'll definitely try it! – user3283988 Apr 01 '14 at 21:15

0 Answers0