Cannot return select query value with mysql and node js

I am new to node js. Now I am trying to set the select query return value in mysql using node js .... I am using the node -mysql package ...

code example

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 always undefined. I know this is an asynchronous call. will someone tell me how to set the value for this variable.

Thanks Deepak

+6
source share
4 answers

Since the database query is asynchronous, your retValue variable is not set 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 
+1
source

Retality will only be available in the scope of what you put in the sequence of the result. This way you can do something similar to record your result:

 var connection = mysql.createConnection({ host : "localhost", user : "root", password: "root123", database: "testdb" }); var retValue = undefined; var query = connection.query('SELECT * FROM tblData;', function(err, results, fields) { console.log(results); // Here continue logic you needed with results from table }); 
0
source

Move console.log inside function processRow(rows) so it looks like

 function processRow(rows) { retValue = rows; console.log(retValue); } 

also change

 processRow(row, function() { retValue = row; }); 

For

 processRow(row); 

The second parameter was not used.

0
source

I cannot get the result from scope ... I want to assign and return a value like this

fucntion () getResults {... ... var retValue = undefined;

var query = connection.query ('SELECT * FROM tblData;', function (err, results, fields) {retValue = results;});

return retValue};

var ret = getResults (); console.log (RET);

0
source

Source: https://habr.com/ru/post/986112/


All Articles