0

I'm pretty new to Javascript and node.js and I'm having some trouble getting this to work. As far as I know, this should produce the expected result but I'm having some rather weird outputs (cf. comments).

function getHistoryFromDb() {
    var rows=1;
    pool.getConnection(function (err, connection) {
        // rows = 1
        console.log(rows);
        connection.query('SELECT * FROM messages', function (error, results, fields) {
            connection.release();
            if (error) throw error;
            // rows = 1
            rows = results;
            // rows = the expected output (array of objects)
        });
    });
    // rows = 1
    return rows;
}

Thanks for your help!

EDIT: Looks like it's more an issue linked to the execution being asynchronous EDIT2: Problem solved, had to use callbacks instead of trying to use returns...

aslad
  • 120
  • 11
  • by the time the function returns, it has not yet completed the callbacks of getconnection() and connection.query(), so the value in rows is still the initial value. Instead of returning the value, your function should accept a callback as parameter, and invoke it with the result. – PA. Mar 14 '17 at 22:31
  • this has nothing to do with scope, it's more to do with getting a value from asynchronous function – Jaromanda X Mar 14 '17 at 22:38
  • Put a `console.log()` call before the line `rows = results;` and another before the line `return rows;`. Then look at the order in which the calls happen. That should help you understand what's going on. The return call is happening BEFORE the assignment to `rows`. – RJM Mar 14 '17 at 22:47
  • Thanks a lot guys, I think I'm getting it, now I just have to find a way to make it synchronous or to make a callback to return only after the value has been set (I'll have to look into that). – aslad Mar 14 '17 at 22:49

1 Answers1

0
    function getHistoryFromDb(callback) {
        var rows=1;
        pool.getConnection(function (err, connection) {
            // rows = 1
            console.log(rows);
            connection.query('SELECT * FROM messages', function (error, results, fields) {

                if (error) throw error;
                // rows = 1
                rows = results;
                connection.release();
               callback(null, rows);


            });
        });

    }

node.js is async so you return your rows before your db query is executed. you need to use callbacks

function handleDBQuery(err, result) {
    if (err) {


        return;
    }

    // do something with result
}

getHistoryFromDb(handleDBQuery);
gmed
  • 140
  • 1
  • 10