N
N
Nikolai2015-06-10 20:58:19
MySQL
Nikolai, 2015-06-10 20:58:19

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();
}

How can I get the value of function selectDB in function accept?
I apologize for the stupid question - with javascript, you still don’t understand many things. I suppose connection.query will return some object, but I looked at its output in the node.js console and did not find a method in it that returns the result of the callback function.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur Shemsedinov, 2015-06-10
@KolyaniuS

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 */ });

By the way, maybe this library will make your life easier: https://www.npmjs.com/package/mysql-utilities
Article on it: habrahabr.ru/post/198738

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question