How To Return Value From Node.js Function Which Contains Db Query
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.
Solution 1:
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.
functionfetchGameList(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.returncallback(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);
Post a Comment for "How To Return Value From Node.js Function Which Contains Db Query"