嵌套数据库查询完成后进行回调

时间:2014-02-06 16:31:35

标签: javascript node.js callback

我的nodejs app做的一切都很好,但由于嵌套的数据库查询,我无法知道进程是否完成。

这个过程就像:

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 
        }); 
}

我想在循环和查询完成时调用callback,这样我就可以关闭connection或退出应用。

有什么想法吗?

我尝试使用asyncconcat方法,但我无法弄清楚如何使用。

1 个答案:

答案 0 :(得分:1)

脏解决方案可以是计数器,每次启动都会增加,完成后会减少...

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 
        }); 
}