Search code examples
javascriptnode.jsvariablessocket.ioglobal-variables

Fetch variable from function into other function (under same function)


I am pretty new to Javascript, nodejs and socket io, so far everything has worked out, until I needed a new function which pulls data from multiply tables instead of just one table, when it's just one table it works fine, since I can emit from inside the function, but this new function, need to increase a number a few times and then emit it, but for some reason I can't get it to increase from the fetched data inside the query function.

This is my function

socket.on("db_rows", function() {
    setInterval(function() {
        
        var rows = 0;
        
        connection.query("SELECT COUNT(id) AS c FROM `systemusage`", function(error, result) {
            rows += result[0].c;
        });
        
        connection.query("SELECT COUNT(id) AS c FROM `temperature`", function(error, result) {
            rows += result[0].c;
        });
        
        connection.query("SELECT COUNT(id) AS c FROM `bmp280`", function(error, result) {
            rows += result[0].c;
        });
        
        console.log(rows);
        
        //var rows = (dbs.a + dbs.b + dbs.c);
        
        var value = (rows).toLocaleString(
            undefined,
            { minimumFractionDigits: 0 }
        );
            
        io.emit("db_rows", value);
    }, 2000)
});

the rows variable doesn't get increased which means that rows is always 0 and I can't figure out a way to get the fetched data outside of the query function, can someone guide me in the right direction?

edit: I have been googling, but none of the answers has helped out.


Solution

  • connection.query does not wait for a result so all three calls will be executed immediately and on the line console.log(rows); you won't have the correct accumulated value.
    You either need to wrap all three calls into promises or use their async counterparts if any.

    await new Promise((resolve, reject) => {
      connection.query("SELECT COUNT(id) AS c FROM `systemusage`", function(error, result) {
              if (error) {
                 reject(error);   
              }
                rows += result[0].c;
                resolve();
            });  
    })
    

    Also you will need to indicate that a callback for setInterval is now an async function:

    setInterval(async function() {
    ...
    })