Answer the question
In order to leave comments, you need to log in
How to return the result of the callback function of a select query in felixge/node-mysql?
Good afternoon!
I can't figure out how to return the result of SELECT execution from the query callback function.
The bottom line is this: there is a node.js server that accepts POST requests from the client and, in accordance with this, performs certain actions with the mysql database. I figured out the recording and update to the database - everything works. But I can not understand how to return a selection by select from a table in the database. For clarity, here is a part of the code:
function accept(req, res) {
if (req.method == "POST") {
var requestBody = '';
req.on('data', function(data) {
requestBody += data;
});
req.on('end', function() {
var formData = qs.parse(requestBody);
var login = formData.login;
//Далее нужно проверить существование записи в БД
//и если такой нет то сделать новую запись в БД, иначе обновить существующую
selectDB(login);
// Здесь нужно получить результат чтобы запустить условие
if (selectDB(login)) ... updateDB(login,score);
else insertDB(login,score);
....
});
// И есть некая функия selectDB
function selectDB(param1) {
var connection = mysql.createConnection({
host : '',
user : '',
password : '',
database : ''
});
connection.connect();
connection.query(
{sql: 'SELECT * from users where login = ?',
values: [param1]
},
function(err, results, fields) {
if (err) return err;
// console.log(results) - возвращает результат выполения запроса в БД, но return results - возвращает undefined
return results;
}
);
connection.end();
}
Answer the question
In order to leave comments, you need to log in
Add a parameter to selectDB(param1, callback)
and call it instead of return results
. Then, in this newest parameter, pass the function that should receive the result and it will receive it as a parameter. It is recommended to do not just callback(results)
, but to forward the error to the top so that it can be processed: callback(err, results)
. Then the call will look like:
selectDB(param1, function(err, result) { /* тут будут доступны выбранные данные в result */ });
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question