I would like to store result from mysql query in an array ( docAutocomplete) and after all the query completed I wanted to see the final array. I am using async series for this purpose. The issue is the array doesn't print anything as it looks like doesn't have any data at the function(err,results).
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));
});
Current output is something like below;
[ 'one', 'two' ]
[] // value of docAutocomplete array. Should have something here First Name and Last name
connection.query
is asynchronous, so the first callback is called before the query is finished. You should call your first callback only when the suery has terminated, like this :
// ...
function(callback) {
connection.connect();
connection.query('select x from a; select b from a', function(err, rows, fields) {
// ...
callback(null, 'one'); // HERE
});
// NOT HERE
},
// ...