0

When I run this function I get null when it comes back because I have the return inside the mysql query how can i solve this?

function CheckStorage(Host, Slots, SSLocation) {
    connection.query("SELECT * FROM `machines` WHERE `shost` LIKE '" + Host + "' AND `location` LIKE '" + SSLocation + "' AND `slotsa` >= " + Slots + "", function(err, rows, fields) {
        if(rows[0]) {
            console.log(rows[0]["ip"]);
            return rows[0]["ip"];
        } else {
            return false;
        }   
    });
}
j08691
  • 204,283
  • 31
  • 260
  • 272
  • The function is async.. callbacks is the answer. – Mr. Alien May 21 '17 at 19:14
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Mr. Alien May 21 '17 at 19:16

1 Answers1

0

connection.query is an asynchronous function so CheckStorage returns before connection.query is finished. You need to pass in a callback function which handles the query results to CheckStorage and then call that function when your query finishes.

function CheckStorage(Host, Slots, SSLocation, callback) {
    connection.query("SELECT * FROM `machines` WHERE `shost` LIKE '" + Host + "' AND `location` LIKE '" + SSLocation + "' AND `slotsa` >= " + Slots + "", function(err, rows, fields) {
        if(rows[0]) {
            console.log(rows[0]["ip"]);
            if (typeof callback == "function") {
               callback(rows[0]["ip"]); 
            }
        }  
    });
}
Ryan Tuosto
  • 1,941
  • 15
  • 23