Reputation: 1727
In all tutorials I searched the web, they print the rows/result using console.log
the from the mysql query. In my case, I want to store that value to manipulate it in a function. The problem is that node doesn't wait. Can you help me in catching the rows in such example? How can I store the rows in a variable?
con.connect(function (err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result) {
if (err) throw err;
console.log(result);
});
});
I tested one of the solutions but I got [] when trying to get result/rows out of the function. I want to use the result in the savedServices: []
see below:
Upvotes: 0
Views: 1071
Reputation: 3469
Give a fresh start with a simple project
Follow below commands
mkdir testdb
cd testdb
npm install --save mysql
npm install --save async
Create a test.js file
vim text.js
Now put below code in the test.js file
var mysql = require('mysql');
var async = require('async');
var con = mysql.createConnection({
host: "localhost",
database: "mydb",
user: "user",
password: "pass"
});
var myrows = [];
async.waterfall([
function(callback) {
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = 'select * from users limit 5';
con.query(sql, function (err, result) {
if (err) throw err;
result.forEach(function(item) {
//console.log(item);
myrows.push(item);
});
callback(null, myrows);
});
});
}
],
// optional callback
function(err, myrows) {
console.log("myrows:::");
console.log(myrows);
});
now test the file
node test.js
You should see results like this:
Connected!
Result: [object Object],[object Object],[object Object],[object Object],[object Object]
Hope this helps!
Upvotes: 2