最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node JS MySQL query function not returning result - Stack Overflow

programmeradmin5浏览0评论

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

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

Share Improve this question edited May 5, 2015 at 20:06 Mike 'Pomax' Kamermans 53.8k17 gold badges125 silver badges176 bronze badges asked May 5, 2015 at 19:55 SystemX17SystemX17 3,7154 gold badges27 silver badges36 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论