node.js - async.whilst with internal callback -


i trying loop while count of array less 50, or if loop has gone through more 14 iterations. seems perfect use async.whilst.

however, complication work function has asynchronous query inside of (a database query).

here simple version of code:

var items = []; var key = 20150713; var iterations = 0;  async.whilst(     function(){         return items.length < 50 || iterations < 14;     },     function(callback){         iterations+=1;          dbquery("my query", function(err, res){             key -=1;             //add res items.             callback();         });     },     function(err){      });     

of course code doesn't work because dbquery() returns immediately, async.whilst blows through 14 iterations , returns empty array before first dbquery returns.

how handle async.whilst waits return of inner function before running again?

or async.whilst not suited task?

you're using correctly. only, code you're posting doesn't you're doing result:

async.whilst(     function(){         return items.length < 50 || iterations < 14;     },     function(callback){         iterations+=1;          dbquery("my query", function(err, res){             key -=1;             //add res items.             callback();         });     },     function(err){         // function called when whilst completes         // or when there's error          if (!err) {             // use items:             console.log(items);         }         else {             console.log('oops.. went wrong somewhere');         }     } ); 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -