I am new in node js, Now I am trying to set a return value of select query in mysql using node js....I am using node-mysql package...
example code
var mysql = require('mysql');
var connection = mysql.createConnection({
host : "localhost",
user : "root",
password: "root123",
database: "testdb"
});
var retValue = undefined;
var query = connection.query('SELECT * FROM tblData;');
query
.on('error', function(err) {
// Handle error, an 'end' event will be emitted after this as well
})
.on('fields', function(fields) {
// the field packets for the rows to follow
})
.on('result', function(row) {
// Pausing the connnection is useful if your processing involves I/O
connection.pause();
processRow(row, function() {
retValue = row;
});
})
.on('end', function(row) {
});
connection.end();
function processRow(rows)
{
retValue = rows;
}
console.log(retValue);
retValue
is always undefined. I know it is asynchronous call. anyone tell me how to set value for this variable.
Thanks Deepak
Once you have MySQL up and running on your computer, you can access it by using Node. js. To access a MySQL database with Node. js, you need a MySQL driver.
Since database query is an asynchronous opreation, your variable retValue
has not been set yet at the time you call console.log(retValue)
.
var retValue;
var query = connection.query('SELECT * FROM tblData;');
query
.on('error', function(err) {
// Handle error, an 'end' event will be emitted after this as well
})
.on('fields', function(fields) {
// the field packets for the rows to follow
})
.on('result', function(row) {
// Pausing the connnection is useful if your processing involves I/O
connection.pause();
processRow(row);
console.log(retValue); //retValue is now set
})
.on('end', function(row) {
});
connection.end();
function processRow(rows)
{
retValue = rows;
}
console.log(retValue); // undefined, retValue has not been set yet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With