1

Okey so I think this has to do something with scoping, but im fairly new to javascript.Inside the function of the database query totalSum has an value, but when I ask for the value outside the function it says its 0. Could someone help me out?

 socket.on('sumDoughnut', function(data){

    var totalSum = 0;


        mysqlConnection.query('SELECT SUM(value) AS Total FROM doughnut', function(err, row, results){
                    if(err) {io.to(socket.id).emit('err_client', { code : 22 });console.log("MySQL error: " + err);if(err.code === 'PROTOCOL_CONNECTION_LOST'){handleDisconnect();}}
                    totalSum = row[0].Total;
                    console.log("here it is " + totalSum);
                });

        console.log(totalSum + " totalSum")
    }
Nick
  • 85
  • 7
  • Try defining `var totalSum = 0` outside of `sumDoughnut` event – guest271314 Jun 25 '16 at 23:35
  • 3
    It's a matter of timing. The query callback is asynchronous and thus is not executed until some time LATER, long after your second `console.log()` statement has executed. Any code that expects to use the new `totalSum` value should be inside the callback, not after it. – jfriend00 Jun 25 '16 at 23:35
  • @guest271314 Tried that but aint working – Nick Jun 25 '16 at 23:37
  • The scope is totally fine. It's just the fact that all that database code executes way after your log happens. – Farzher Jun 25 '16 at 23:37
  • @jfriend00 but I need to use the value right after the query so what can I do so that I can use the value instantly? – Nick Jun 25 '16 at 23:38
  • 3
    @Nick you need to consume it after it is received.... can't eat a pizza before it gets delivered now can you? – charlietfl Jun 25 '16 at 23:39
  • @Nick _"I need to use the value right after the query"_ Use the value within `.query` callback function – guest271314 Jun 25 '16 at 23:39
  • @Nick `console.log("here it is " + totalSum)` do whatever you need to there – Farzher Jun 25 '16 at 23:39
  • 3
    This is how asynchronous code works in Javascript. You put the code that uses `totalSum` INSIDE the callback so you can use the value right where it is provided. Or you can call a function from within the callback and pass the function that value. It is not usable anywhere else. This is how async programming works in Javascript. Resistance is futile! Programming with promises instead of plain callbacks makes the writing of the code a bit more pleasant and makes error handling a ton easier. – jfriend00 Jun 25 '16 at 23:41
  • Thx guys for helping me out :) – Nick Jun 25 '16 at 23:45
  • @charlietfl I think that's the best way of explaining asynchronous behaviour. Will use it from now on ;) – jonathanGB Jun 25 '16 at 23:45
  • @jfriend00 especially like .. *"Resistance is futile"* ... "But that's not how I designed my app!!" – charlietfl Jun 25 '16 at 23:46
  • 1
    @Jonathan actually I stole that from escaparrello ( not sure of spelling) ... but it does put things in obvious laymans terms – charlietfl Jun 25 '16 at 23:47
  • @Nick did the proposed answer worked for you? If so, accept it, so people with the same problem in the future will know it works. – jonathanGB Jun 25 '16 at 23:52

1 Answers1

1

As mentionned in the comments, the scope is right. The problem is the call to console.log should be in the callback, not outside.

If you don't put it in the callback, the console.log call will execute immeditaly after the database call, not waiting for the response of the DB. The callback will be triggered as soon as the DB returned the values.

This will fix it:

socket.on('sumDoughnut', function(data){
    var totalSum = 0;

    mysqlConnection.query('SELECT SUM(value) AS Total FROM doughnut', function(err, row, results){
        if(err) {io.to(socket.id).emit('err_client', { code : 22 });console.log("MySQL error: " + err);if(err.code === 'PROTOCOL_CONNECTION_LOST'){handleDisconnect();}}

        totalSum = row[0].Total;
        console.log(totalSum + " totalSum")
    });
}
jonathanGB
  • 1,500
  • 2
  • 16
  • 28