This question already has an answer here:
这个问题在这里已有答案:
- How do I return the response from an asynchronous call? 31 answers
如何从异步调用返回响应? 31个答案
I'm learning Node.js and I'm just starting to work with some MySQL connections. I have a function which is supposed to get a set of rows from the database, which it does correctly. However, I don't know how to return that set of rows afterwards. I tried two options (both explained in comments within the code segment below.
我正在学习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
}
So, the question is, how do I return the correct value of ret
(7 in this case)? Am I even structuring this properly?
所以,问题是,如何返回正确的ret值(在这种情况下为7)?我是否正确地构建了这个?
1 个解决方案
#1
10
You need to pass a callback into your function. Convention is that the callback takes an error (or null
if none happened) as the first argument, and results as other arguments.
您需要将回调传递给您的函数。惯例是回调接受错误(如果没有发生则为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);
});
}
You can now do something along the lines of:
您现在可以执行以下操作:
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);
#1
10
You need to pass a callback into your function. Convention is that the callback takes an error (or null
if none happened) as the first argument, and results as other arguments.
您需要将回调传递给您的函数。惯例是回调接受错误(如果没有发生则为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);
});
}
You can now do something along the lines of:
您现在可以执行以下操作:
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);