0

I'm trying to use a SQL query with NodeJs but the async part really mess me up. When i print the return it gets "undefined". How can i sync this?

    function SQL_test(blos) {
  DB.query("Select profesor_id from materiador where materia_id = '"+blos+"';",function (err, results, fields) {

    return results;

  });

}

console.log(SQL_test(1));

Thanks!

2 Answers 2

1

So your answer is currently a promise. You'll have to read about Async and Await to do more synchronous JS.

Most of the JS for NodeJS is currently async. Below is a rewritten version of your example properly utilizing the callback method for your DB.

function callback (err, results, fields) {
    if (err) {
        console.log(err);
        return err;
    }
    console.log(results, fields);
    return results;
};

function SQL_test(blos) {
    DB
        .query("Select profesor_id from materiador where materia_id = '"+blos+"';", callback);
}
SQL_test(1);

To do the same thing synchronously you have to still have an outer level promise, otherwise Async and Await won't work how you want it to. There's no true synchronous way to handle this is javascript because it executes without waiting for the response.

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

Comments

0

function sqlTest(blos) {
  return new Promise((resolve, reject) => {
    DB.query(
      `Select profesor_id from materiador where materia_id = '${blos}';`,
      (err, results) => {
        if (err) return reject(err)
        resolve(results)
      }
    );
  }
)

sqlTest(1)
  .then(console.log)
  .catch(console.error)

3 Comments

Its working! But how can i replace the "console.log" under the sqlTest with a variable assignment. Like .then(p = (querys result))
Welcome to asynchronous programming, German :) The answer is nohow. Read about async/await - it mimics synchronous behavior being asynchronous indeed.
inside then can be code that follows: (result) => { const pAssignmentAsYouWanted = result; } Pretty useless and can be improved by es6+, but.. you asked - I answered :)

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.