0

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!

1 Answer 1

4

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());
});
Sign up to request clarification or add additional context in comments.

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.