-2
function emailExist(e) {
    const sqlstmt = "SELECT email FROM somewhere WHERE email = ? LIMIT 1";
    db.query(sqlstmt, [e], (err, result) => {
        //supposed to return 0 or 1
        return result.length
    });
}

console.log(emailExist('someone@gmail.com')); //returns undefined

I tried using variables, still returned undefined

  • 1
    The `return` stmt you're looking at is for the inner anonymous function passed to `db.query`. So, there is no `return` stmt for `emailExist` – vrintle Dec 21 '20 at 17:53
  • Hi Lanrer, could you elaborate more on the issue? what do you mean by "I tried using variables"? did you tried storing emailExist('someone@gmail.com') in a variable and print it? – Mario Perez Dec 21 '20 at 17:59
  • no I declared a variable just after 'function emailExist(e) {', then I set it like 'var something = result.length' and then I returned it 'return something' and it still gave me undefined – Lanre Bello Dec 21 '20 at 18:08

1 Answers1

2

The problem is that you are trying to return a value from the callback.

To get the value from the callback, which will be called after a certain period of time. There are several ways to solve this problem, for example, you can wrap your callback in a Promise:

function query(sqlstmt) {
  return new Promise((resolve, reject) => {
    db.query(sqlstmt, [e], (err, result) => {
      if(err) {
        return reject(err);
      }
      resolve(result.length);
  });
  })
}

async function emailExist(e) {
  const sqlstmt = "SELECT email FROM somewhere WHERE email = ? LIMIT 1";
  const result = await query(sqlstmt);
  return result;
}
xom9ikk
  • 2,159
  • 5
  • 20
  • 27
  • it returned 'Promise { }' – Lanre Bello Dec 21 '20 at 18:10
  • You are most likely calling the `emailExist` function without waiting for it to complete. The call must be with the `await` keyword, or try using the chainable `Promise` like this: `emailExist.then ((result) => console.log (result))` – xom9ikk Dec 21 '20 at 18:16