Rohan Sharma Rohan Sharma - 3 years ago 192
Node.js Question

Node.js boolean variable not changing value

I have following code:

app.post('/', function (req, res)
{
/*
connection is created with mysql
*/
var success = true
connection.query(sql, [values], function (err, result)
{
success = false
})
connection.end()
console.log(success)
}
)


The output of this is
true
. How do I change the value of success from inside of connection.query?

Answer Source

Though the code block in which success is redefined success = false; is "before" console.log(result) in terms of line numbers. It actually takes place after. connection.query() is invoked with a function which will get invoked at a later time, after the query has completed.

There's at least 3 different ways to handle this.

the callback style this is simply wrapping the code you want to execute in the conn.query anonymous function like so

app.post('/', function (req, res)
    {
        /*
        connection is created with mysql
        */
        var success = true;
        var callback = function(result) {
            success = result;
            console.log(success);
            connection.end()
        };

        connection.query(sql, [values], function (err, result)
        {
            callback(result);
        });
    }
);

the promise style if conn.query() returns returns a promise then you could do something like this:

app.post('/', function (req, res)
    {
        /*
        connection is created with mysql
        */
        var success = true;
        var callback = function(result) {
            success = result;
            console.log(success);
            connection.end()
        };

        connection.query(sql, [values]).then(callback);
    }
);

more info on Promises

Also, if you're using the mysql driver for node, you can also use promise-mysql to use promises.

the await style which operate more intuitively for those who aren't used to event-driven programming. Assuming your conn.query() supports Promises, you could use await and it would look something like this:

app.post('/', function (req, res)
    {
        /*
        connection is created with mysql
        */
        var success = true;
        await connection.query(sql, [values], (result) => success = false);
        console.log(success);
        connection.end();
    }
);

more info on await

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download