3

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; }

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I understand, so essentially it "appears" that if I put the console.log(result) in the function itself - it has access to the result as it is only after the query has completed the the log event is called. Where my initial var loginResult is being logged while the query is still running. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.