我想将 mysql 查询的结果存储在一个数组中(docAutocomplete),在所有查询完成后我想看到最终的数组。我为此目的使用异步系列。问题是数组不打印任何内容,因为函数看起来没有任何数据(错误,结果)。
var mysql = require('mysql'),
async = require("async");
var connection = mysql.createConnection({
host: 'xx',
user: 'xx',
password: 'xx',
database: 'xx'
multipleStatements: true
});
var docAutocomplete = [];
async.series([
function(callback) {
connection.connect();
connection.query('select x from a; select b from a', function(err, rows, fields) {
if (err) throw err;
for (var i = 0; i < rows[0].length; i++) {
docAutocomplete.push({
" First Name": rows[0][i].x
})
}
for (var i; i < rows[1].length; i++) {
docAutocomplete.push({
"Last Name": rows[1][i].b
})
}
});
callback(null, 'one');
},
function(callback) {
connection.end();
callback(null, 'two');
}
],
function(err, results) {
console.log(results);
console.log(JSON.stringify(docAutocomplete));
});
当前输出如下所示;
[ 'one', 'two' ]
[] // value of docAutocomplete array. Should have something here First Name and Last name
最佳答案
connection.query
是异步的,因此第一个回调会在查询完成之前调用。您应该仅在 suery 终止时调用第一个回调,如下所示:
// ...
function(callback) {
connection.connect();
connection.query('select x from a; select b from a', function(err, rows, fields) {
// ...
callback(null, 'one'); // HERE
});
// NOT HERE
},
// ...
关于javascript - 带有node-mysql输出到数组的异步系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33890131/