我的nodejs应用程序做得很好,但是由于嵌套的数据库查询,我无法知道该过程是否完成。
该过程就像:
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
或退出应用程序。
有什么想法吗?
我尝试使用异步库concat方法,但我无法弄清楚如何。
肮脏的解决方案可以是计数器,每次启动时增加,并在结束后减少...
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
});
}