Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js get result from mysql query

Tags:

node.js

mysql

why I cannot get results?

var sql_data = connection.query(sql, function(error, results, fields) {
    if(error) {
        console.log(error);
            return;
    }
    var rows = JSON.parse(JSON.stringify(results[0]));
    console.log(rows);
});
console.log(rows);

fiirst console.log is ok, display object, but second says:

ReferenceError: rows is not defined

what is wrong?..

like image 279
Pavel Prokofiev Avatar asked Feb 21 '17 17:02

Pavel Prokofiev


2 Answers

You shouldn't assign asynchronous function to a variable just like you do in first line of your code. You just call it and perform operations on the result with use of callback methods (which in this case is function(error, results, fields). Your code should look like below

connection.query(sql, function(error, results, fields) {
    if(error) {
        console.log(error);
        return;
    }
    var rows = JSON.parse(JSON.stringify(results[0]));

    // here you can access rows
    console.log(rows);
});

// here it will be undefined
console.log(rows);

The rows variable in second console.log will be undefined because it was defined in different scope. Even if you would do var rows above the connection.query, it would still be undefined, because you assign it's value inside asynchronous function's callback. You need to read more about this kind of operations.

like image 127
piotrbienias Avatar answered Oct 04 '22 12:10

piotrbienias


You should use then Promise if you want to get the query result. I prefere it to be onest. The Promise runs the command async.

function getDomain() {
    return result = await dbQuery('SELECT name FROM virtual_domains ORDER BY id;');
}

// * Important promise function
function dbQuery(databaseQuery) {
    return new Promise(data => {
        db.query(databaseQuery, function (error, result) { // change db->connection for your code
            if (error) {
                console.log(error);
                throw error;
            }
            try {
                console.log(result);

                data(result);

            } catch (error) {
                data({});
                throw error;
            }

        });
    });

}
like image 41
Martijn van Wezel Avatar answered Oct 04 '22 11:10

Martijn van Wezel