这是我的NodeJS代码,我想在执行查询后返回csvFile数组,但我首先返回一个空数组,然后执行查询。我在getSummary函数中调用getDetection函数。这两个函数都在执行查询。有人可以帮帮我吗?
function getSummary(req, res) {
var result = [];
var csvFile = new Array();
//console.log(csvFile);
pool.getConnection(function(err, connection){
if (err) {
res.json({"code" : 100, "status" : "Error in connection database"});
return;
}
//var result = [];
var option = req.body;
//console.log(option.type);
connection.query("SELECT DISTINCT name FROM dgh WHERE name LIKE ? ", ['%' + option.type.toUpperCase() + '%'],
function(err, rows, fields) {
connection.release();
if (err) {
throw err;
} else {
for (var i = 0; i < rows.length; i++) {
var row = rows[i].name;
result.push(row);
getDetection(result[i], function(result) {
if (err) {
throw err;
} else {
var count = result.count;
var maxD = result.maxD;
var array = new Array(count, maxD);
csvFile.push(array);
//console.log(csvFile);
}
});
}
}
});
})
console.log(csvFile);
res.csv(csvFile);
}
getDetection函数:
function getDetection(filename, callback) {
pool.getConnection(function(err, connection){
if (err) {
res.json({"code" : 100, "status" : "Error in connection database"});
return;
}
connection.query("SELECT hour, minute, second FROM dgh WHERE name = ?", [filename],
function(err, rows, fields){
connection.release();
if (err) {
throw err;
} else {
var count = 0;
var maxD = 0;
for (var i = 1; i < rows.length; i++) {
var time1 = rows[i].hour * 3600 + rows[i].minute * 60 + rows[i].second;
var time2 = rows[i - 1].hour * 3600 + rows[i - 1].minute * 60 + rows[i].second;
if (time2 - time1 > 60) {
count = count + 1;
maxD = Math.max(maxD, time2 - time1);
}
}
callback({count:count, maxD:maxD});
}
})
})
}
答案 0 :(得分:0)
Node.js是异步的。如果 getDetection 是循环的异步函数,则不会按预期执行。
for (var i = 0; i < rows.length; i++) {
var row = rows[i].name;
result.push(row);
getDetection(result[i], function(result) {
if (err) {
throw err;
} else {
var count = result.count;
var maxD = result.maxD;
var array = new Array(count, maxD);
csvFile.push(array);
//console.log(csvFile);
}
})
}
}
截至目前,for循环只会通过 getDetection 函数并完成迭代。这会导致变量 csvFile 为空。
我建议您使用 npm 安装 async 包。
npm install --save async
安装后
async.each(rows, function(name, callback) {
result.push(name)
getDetection(name, function(item){
if (err) throw err
var count = item.count
var maxD = item.maxD
var array = new Array(count, maxD)
csvFile.push(array)
callback()
})
}, function(err){
if (err) {
//Handle error here that occurred during iteration
} else { //finished all iteration
console.log(csvFile)
res.csv(csvFile)
return
}
})