如何从包含数据库查询的Node.js函数返回值

我正在学习Node.js,我刚开始使用一些MySQL连接。 我有一个函数应该从数据库中获取一组行,这是正确的。 但是,我不知道如何返回那一组行。 我尝试了两个选项(在下面的代码段中的注释中都有解释。

function fetchGameList(){ var ret = 0; connection.query("SELECT * from tbl", function(err, rows, fields) { //some stuff happens here, and 'ret' is set to a vlue, for instance //ret = 7; //ret has the value 7 here, but if I put 'return ret' here, nothing is returned }); return ret; //returns 0 because Node is asynchronous and the query hasn't finished yet } 

所以,问题是,如何返回ret的正确值(在这种情况下是7)? 我甚至正确地构造这个?

你需要传递一个callback到你的函数中。 约定是,callback函数接受一个错误(如果没有发生,则返回null )作为第一个参数,结果作为其他参数。

 function fetchGameList(callback) { var ret; connection.query("SELECT * from tbl", function(err, rows, fields) { if (err) { // You must `return` in this branch to avoid using callback twice. return callback(err); } // Do something with `rows` and `fields` and assign a value to ret. callback(null, ret); }); } 

你现在可以做一些事情了:

 function handleResult(err, result) { if (err) { // Just an example. You may want to do something with the error. console.error(err.stack || err.message); // You should return in this branch, since there is no result to use // later and that could cause an exception. return; } // All your logic with the result. } fetchGameList(handleResult);