SystemX17
SystemX17

Reputation: 3715

Node JS MySQL query function not returning result

I am running a MySQL query inside a .js file running on Node JS. I have the connection setup ok and the query works but when I try returning the result back to the original call it doesn't seem to work.

function sqlQuery(query){
	console.log("Running query");
	var conn = connection();
	var result = false;
	conn.query(query, function(err, rows, fields) {
	    conn.end();
	    if (!err){ result = rows; } else { result = err; }
	});
	return result;
}

var loginResult = sqlQuery("SELECT * FROM `players`");
console.log(loginResult);

If I use the following code it does write the result to the console inside the query but not the final "loginResult". I am not getting any errors so my question is - is there an error in the way I am getting the returned result?

if (!err){ result = rows; console.log(rows); } else { result = err; }

Upvotes: 3

Views: 6487

Answers (1)

Virtually everything in Node.js is asynchronous, and SQL query functions definitely are. You're calling conn.query(query, callback), which means that query is called, and then once there is a result at some point in the future, your callback function gets called with the result for you to work with. So:

conn.query(query, function runThisEventually(err, rows, fields) {
    if (err) {
      console.error("One or more errors occurred!");
      console.error(err);
      return;
    }
    processResults(rows, fields);
});

You won't get the result immediately after calling conn.query(...), so your code gets to do "other things" in the mean time, and at some point, your callback will be triggered and you can pick up result processing there.

Upvotes: 7

Related Questions