Tuesday 9 May 2017

nodejs-async: return mysql query result in for loop

I have three operations to do one after another

1.Fetch some rows from db

2.Another mysql query in forloop for getting some data and store in variable

3.Display the data

For that i am using async waterfall method.

async.waterfall([
            function(callback){
                //first sql and pass the result to second function
                collection.getAllCollections(function (status,error,result) {
                    callback(null,result);
                });
            },
           //running another query in loop with result with previous
            function(result, callback){
                for(var i=0;i<result.length;i++){
                    collection.getImages(result[i].id,function (status,error,user) {
                        //append the query result to old result
                         result[i]['users'] = user;
                    });
                }
                callback(null,result);
            }
        ], function (err, result) {

            console.log("result",result);
        });

But the problem final result does not contains the user results because the second query(query in for loop is asynchronous)



via Jabaa

No comments:

Post a Comment