6

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?..

Pavel Prokofiev
  • 449
  • 2
  • 4
  • 14

2 Answers2

9

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.

piotrbienias
  • 7,201
  • 1
  • 28
  • 33
6

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

        });
    });

}
Martijn van Wezel
  • 1,120
  • 14
  • 25