Cool cow facts
Cool cow facts

Reputation: 37

mySQL query in node.js is returning undefined

When making an sql query my function is returning undefined. I'm unsure how to fix this and was confused when I googled the problem. Here is a section of my code:

function randomfact() {
let sql = 'SELECT id FROM facts ORDER BY RAND() LIMIT 1;';
let query = db.query(sql, (err, result) => {
    if (err) {
        throw err;
    }
    else {
        return result;
    }
});
}

const app = express();

app.get("/", function(req, res) {
   res.send(randomfact());
   console.log(randomfact());
});

My best guess as to the issue is that I am returning an incorrect datatype but I am unsure on how to fix it.

Any advice is good advice thanks!

Upvotes: 0

Views: 3707

Answers (1)

Eranga Heshan
Eranga Heshan

Reputation: 5814

Change your randomfact function to return the query result:

function randomfact() {
  let sql = 'SELECT id FROM facts ORDER BY RAND() LIMIT 1;';
  return new Promise((resolve, reject) => {
    db.query(sql, (err, result) => {
      if (err) {
        reject(err);
      }
      else {
        resolve(result);
      }
    });
  });
}

Wait for randomfact to return the result:

app.get("/", async function(req, res) {
   const result = await randomfact();
   res.send(result);
   console.log(randomfact());
});

Upvotes: 4

Related Questions