以下是我的代码:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1',
database : 'test'
});
connection.connect();
data = connection.query('SELECT * FROM deneme', function(err, rows, fields){
if(err) throw err;
veri = rows;
return veri;
});
console.log(data);
当我运行此文件(index.js)时,如下所示
node index.js
它返回一些错误并且不显示数据。
我的mysql数据如下:
INSERT INTO `deneme` (`id`, `name`) VALUES
(1, 'yusuf'),
(2, 'ali');
有什么问题?
错误是:
{ _callback: [Function],
_ended: false,
_callSite: ' at Query.Sequence (/home/yusuf/Masaüstü/node/node_modules/mysql/lib/protocol/sequences/Sequence.js:15:21)\n at new Query (/home/yusuf/Masaüstü/node/node_modules/mysql/lib/protocol/sequences/Query.js:11:12)\n at Protocol.query (/home/yusuf/Masaüstü/node/node_modules/mysql/lib/protocol/Protocol.js:41:24)\n at Connection.query (/home/yusuf/Masaüstü/node/node_modules/mysql/lib/Connection.js:90:25)\n at Object.<anonymous> (/home/yusuf/Masaüstü/node/index.js:10:19)\n at Module._compile (module.js:446:26)\n at Object..js (module.js:464:10)\n at Module.load (module.js:353:31)\n at Function._load (module.js:311:12)\n at Array.0 (module.js:484:10)',
sql: 'SELECT * FROM deneme',
typeCast: true,
nestTables: false,
_resultSet: null,
_results: [],
_fields: [],
_index: 0,
_loadError: null,
_events: { error: [Function], packet: [Function], end: [Function] } }
答案 0 :(得分:1)
你想要同步而不是异步地做某事。
你的问题在这里:
data = connection.query('SELECT * FROM deneme', function(err, rows, fields){
if(err) throw err;
veri = rows;
return veri;
});
console.log(data);
您在执行回调之前记录数据。这就是为什么你需要在其回调中包含代码的原因,所以它说&#34;一旦你完成了数据库结果,就这样做了#34;。
data = connection.query('SELECT * FROM deneme', function(err, rows, fields){
if(err) throw err;
veri = rows;
console.log(veri); // will be logged once its finished
});
您可以通过执行以下操作来访问此功能之外的结果:
var results;
data = connection.query('SELECT * FROM deneme', function(err, rows, fields){
if(err) throw err;
veri = rows;
results = veri;
someOtherFunction();
});
var someOtherFunction = function(){
console.log(results);
}
您可以查看名为async
的模块,该模块擅长做您正在尝试做的事情。
https://github.com/caolan/async
P.S
欢迎来到nodejs。