Maxali
Maxali

Reputation: 1962

Make a callback after nested database queries are done

My nodejs app does everything fine but I am not able to know if the process in done or not because of nested database queries.

The process is like:

function saveToDB(allData, callback) {
       var connection = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            database: 'node'
       }); 
       [].forEach.call( Object.keys( allData ), function( prop ){                                                 

            var conditions = {link: allData[prop]['link']};
            connection.query("SELECT link FROM articles WHERE ?", conditions, function(err, rows, fields) {
                if(rows.length < 1) { 
                    connection.query('INSERT INTO articles SET ?', {
                            link: allData[prop].link,
                            title: allData[prop].title,
                            description: allData[prop].description,
                            pubDate: allData[prop].pubDate
                    }, function(err, result){
                            if(err) throw err; 

                    }); 
                }           
            });   

            //Still there are some 
        }); 
}

I want to call the callback when the loop and the queries are finished, so I can close the connection or exit the app.

Any idea?

I tried to use async libraries concat method, but I cannot figure out how.

Upvotes: 0

Views: 243

Answers (1)

Luan Castro
Luan Castro

Reputation: 1184

the dirty solution can be a counter, increment in each start, and decrease after finish...

function saveToDB(allData, callback) {
       var inProgress = 0;
       function done(){
           if( inProgress <= 0 ) callback();
       }
       var connection = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            database: 'node'
       }); 
       [].forEach.call( Object.keys( allData ), function( prop ){                                                 
            inProgress++;
            var conditions = {link: allData[prop]['link']};
            connection.query("SELECT link FROM articles WHERE ?", conditions, function(err, rows, fields) {
                if(rows.length < 1) { 
                    connection.query('INSERT INTO articles SET ?', {
                            link: allData[prop].link,
                            title: allData[prop].title,
                            description: allData[prop].description,
                            pubDate: allData[prop].pubDate
                    }, function(err, result){
                            inProgress--;
                            if(err) throw err; 
                            done();

                    }); 
                }           
            });   

            //Still there are some 
        }); 
}

Upvotes: 1

Related Questions