German Garay
German Garay

Reputation: 11

NodeJS and SQL with Async

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!

Upvotes: 0

Views: 48

Answers (2)

Enthusiastic Developer
Enthusiastic Developer

Reputation: 762

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)

Upvotes: 0

JacobW
JacobW

Reputation: 876

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.

Upvotes: 1

Related Questions