jov*_*van 6 javascript 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
}
Run Code Online (Sandbox Code Playgroud)
所以,问题是,如何返回正确的值ret(在这种情况下为7)?我是否正确地构建了这个?
qub*_*yte 11
您需要将回调传递给您的函数.惯例是回调将错误(或者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);
});
}
Run Code Online (Sandbox Code Playgroud)
您现在可以执行以下操作:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34917 次 |
| 最近记录: |