用nodejs和node-mysql返回行

我正在发现Nodejs和node-mysql模块。 我有一个小问题。 我find的每一个教程都解释了如何在数据库上进行select,但是他们从不返回行,他们总是logging下来,这对我的情况来说绝对是无用的。

我有一个app.js文件:

// Get continents app.get("/continents", function(request, result) { console.log("Continents : " + database.findAllContinents()); }); 

和一个mysql.js文件:

 exports.findAllContinents = function(connection) { var connection = getConnection(); connection.query('select id, code, name from Continent', function (err, rows, fields) { if (err) { console.log("Error in findAllContinents : " + err) } return JSON.stringify(rows); }); closeConnection(connection); }; 

我怎样才能使该函数返回行在app.js文件中使用它们? 我真的不想在app.js文件中创build连接我想DAO层分离。 你有什么主意吗 ?

另外,如果有人有使用node-mysql而不是ORM(sequelize,persistence.js …)的优点/缺点,

谢谢

query()是一个asynchronous函数,你不能返回任何结果。 因此,任何调用asynchronous函数(比如你的findAllContinents )的函数都不能。

相反,你需要传递一个callback函数( 这里也解释了 ),这将在查询完成时调用:

 // app.js app.get("/continents", function(request, response) { database.findAllContinents(function(err, results) { if (err) throw err; // or return an error message, or something else res.send(results); // as a demo, we'll send back the results to the client; // if you pass an object to 'res.send()', it will send // a JSON-response. }); }); // mysql.js exports.findAllContinents = function(cb) { var connection = getConnection(); connection.query('select id, code, name from Continent', function (err, rows, fields) { // close connection first closeConnection(connection); // done: call callback with results cb(err, rows); }); }; 

至于(不)使用ORM,这真的取决于用例。 我会select一个ORM(我最喜欢的MySQL是天井 ),以防我的应用程序需要多个(复杂)模型,也许它们之间有关联。 另外,ORM提供的抽象使得代码更容易阅读,并且通常允许更容易地将应用程序移植到不同的数据库。