async.whilst with internal callback

时间:2015-07-13 21:01:10

标签: node.js

I am trying to loop while the count of some array is less than 50, or if the loop has gone through more than 14 iterations. This seems like a perfect use for async.whilst.

However, my complication is that my work function has an asynchronous query inside of it (a database query).

Here is a simple version of my 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 to items.
            callback();
        });
    },
    function(err){

    });    

Of course this code doesn't work because dbQuery() returns immediately, so async.whilst just blows through 14 iterations and returns an empty array before the first dbQuery even returns.

How do I handle this so that async.whilst waits for the return of the inner function before running again?

Or is async.whilst not suited to my task?

1 个答案:

答案 0 :(得分:1)

You're using it correctly. Only, from the code you're posting it doesn't look like you're doing anything with the result:

async.whilst(
    function(){
        return items.length < 50 || iterations < 14;
    },
    function(callback){
        iterations+=1;

        dbQuery("my query", function(err, res){
            key -=1;
            //add res to items.
            callback();
        });
    },
    function(err){
        // this function will be called when whilst completes
        // or when there's an error

        if (!err) {
            // use items:
            console.log(items);
        }
        else {
            console.log('OOps.. something went wrong somewhere');
        }
    }
);