Thursday, 25 May 2017

How to hold loop untill async function complete

I am facing problem while executing a async function inside a nested loop. Below is my code

count1 = [1,2,3];
count2 = [1,2];
async.forEach(count1, function(count1, callback){
console.log("aa");
async.forEach(count2, function(count2, callback1){
    console.log("bb");
    connection.query('INSERT INTO customers set ?', data,function(err, result){
        if(err){
            console.log(err);
            callback1(err);
        }
        console.log("success");
        callback1(null);
    }, function(err, result){
        console.log(result);
        callback1(err);

    });
}, function(err){
    callback(err);
});

});

Below is the output of this code

aa
bb
bb
aa
bb
bb
aa
bb
bb
success
success
success
success
success
success

The expected output should be

aa
bb
success
bb
success
aa
bb
success
bb
success
aa
bb
success
bb
success

Please suggest how can i implement a async function that hold the loop untill the function complete its execution.



via k_hotspot

No comments:

Post a Comment