javascript Nodejs MySQL 连接查询返回值到函数调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15635791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nodejs MySQL connection query return value to function call
提问by Aks1357
I am trying get value from database. Trying it out with a demo example. But I am having problem to synchronize the calls, tried using callback function. I am beginner in node.js, so don't know if this is the right way.
我正在尝试从数据库中获取价值。通过演示示例进行尝试。但是我在同步调用时遇到问题,尝试使用回调函数。我是 node.js 的初学者,所以不知道这是否是正确的方法。
FILE 1 : app.js
文件 1:app.js
var data;
var db = require('./db.js');
var query = 'SELECT 1 + 1 AS solution';
var r = db.demo(query, function(result) { data = result; });
console.log( 'Data : ' + data);
FILE 2 : db.js
文件 2:db.js
var mysql = require('./node_modules/mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
});
module.exports.demo = function(queryString, callback) {
try {
connection.connect();
console.log('Step 1');
connection.query(queryString, function(err, rows, fields) {
console.log('Step 2');
if (err) {
console.log("ERROR : " + err);
}
console.log('The solution is: ', rows[0].solution);
callback(rows[0].solution);
return rows[0].solution;
});
callback();
connection.end();
console.log('Step 3');
}
catch(ex) {
console.log("EXCEPTION : " + ex);
}
};
OUTPUT :
输出 :
Step 1
Step 3
Data : undefined
Step 2
The solution is: 2
Referred to this question also, but it didnt solve my problem : nodeJS return value from callback
也提到了这个问题,但它没有解决我的问题: nodeJS return value from callback
回答by robertklep
The issue is this:
问题是这样的:
var r = db.demo(query, function(result) { data = result; });
console.log( 'Data : ' + data);
The console.log
will run before the callback function gets called, because db.demo
is asynchronous, meaning that it might take some time to finish, but all the while the next line of the code, console.log
, will be executed.
在console.log
将运行回调函数被调用之前,因为db.demo
是异步的,这意味着它可能需要一些时间来完成,但所有的,而代码的下一行,console.log
将被执行。
If you want to access the results, you need to wait for the callback function to be called:
如果要访问结果,则需要等待回调函数被调用:
var r = db.demo(query, function(result) {
console.log( 'Data : ' + result);
});
This is how most code dealing with I/O will function in Node, so it's important to learn about it.
这是大多数处理 I/O 的代码在 Node 中运行的方式,因此了解它很重要。