0

Trying to query my database and each time I do, it runs all the queries at the end instead of when I need them in nodejs.

var mysql = require('mysql');

var con = mysql.createConnection({
  host: database.host,
  user: database.user,
  password: database.password,
  database: database.database
});

The connection data I am pulling from a json file.

function getSymbol(id){
var s = "";
con.query("SELECT * FROM Symbol WHERE PlayerID = '" + id + "'", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
    if (result.length < 1) {
        console.log(result);
        s = result[0].Symbol;
    }
    else {
        s = "!";
    }
});
console.log(s);
return s;

}

It all runs at the end of the program wondering if there is a fix or if I should switch to python (seriously considering rewriting all of it at this point).

2 Answers 2

1

The problem is what you have written comes under NIO and it wont wait for executing the next statement unless you ask it to. Try the below code:

async function getSymbol(id){
   var s = "";
   try {
    let result = await con.query("SELECT * FROM Symbol WHERE PlayerID = '" + id + "'")
    if (result.length < 1) {
        console.log(result);
        s = result[0].Symbol;
    }
    else {
        s = "!";
    }
   }catch(error){
        console.log(error);
        throw new error;
   }
    console.log(s);
   return s;
 }

Note: I have used async/await. You can also use Promises

Sign up to request clarification or add additional context in comments.

5 Comments

Ok it now returns [object Promise] instead of nothing to the method call on a console.log, and then after the log it runs the query. Do I also need to migrate the other stuff to a async method and run the return with await.
what is your console.log(s) is printing?
It was returning ! instead of what I have it set to in my database ?.
Can you try changing the query to - "select * from Symbol" and you are getting some result?
I found the issue it was my if case it was wanting less then 1 instead of 1 and now it works, so your original solution was the correct one I just did a dumb. Thank you for the assistance.
0

As mentioned, the method is NOT sync. Your result will be on the callback you pass.

con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("The Data: " + result);
});

More Info: https://www.w3schools.com/nodejs/nodejs_mysql.asp

Moreover, you need to connect first with con.connect( <callback-here> ).

The best way to work with this is to avoid the callbacks for async/wait syntax.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.