2

I have a function that checks if a user is admin or not. If it finds the user id in the database table, it needs to return true, otherwise it needs to return false, but I'm getting undefined. Can you help me?

function isAdmin(useruid) {
  db.query("SELECT * FROM admins", function(err,rows,field) {
    if(!err) {
  
      rows.forEach(function(element) {
        if (useruid === element.uid) {
          console.log("[is admin] Found admins!")
          return true;

        } else {
          console.log("[is admin] User is not admin!")
          return false;
        }
      });
  
    } else {
      console.log(err);
      return false;
    }
  })
}

I added ; on the missing lines. I'm receiving output of the console.logs, but the function is still returning undefined instead of false or true.

It looks like:

function isAdmin(useruid) {
  db.query("SELECT * FROM admins", function(err,rows,field) {

    if(!err) {
      rows.forEach(function(element) {
        if (useruid === element.uid) {
          console.log("[is admin] Found admins!");
          return true;
        } else {
          console.log("[is admin] User is not admin!");
          return false;
        }
      });
  
    } else {
      console.log(err);
      return false;
    }
  })
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
HAZZE
  • 21
  • 3
  • What did you expect would return to variable `rows` if there are no records match your query (not admin)? – HardcoreGamer Aug 10 '21 at 09:51
  • There is matching records, and also if there is no matching records it should return False, but im recieving "undefined" :) – HAZZE Aug 10 '21 at 09:51
  • I see. Please include in your question which line throw the `undefined` error. – HardcoreGamer Aug 10 '21 at 09:53
  • I don't know that. when i run function like: console.log(isAdmin("adminid")); im getting "undefined" edit: also when i put in in if statement it can't work because output is always undefined – HAZZE Aug 10 '21 at 09:55
  • Don't know if this is related but multiple line is missing `;`. Besides, consider adding more console.log for debugging. Like before `if(!err)` – HardcoreGamer Aug 10 '21 at 10:01
  • I added ; on the missing lines so now it looks like: ` function isAdmin(useruid) { db.query("SELECT * FROM admins", function(err,rows,field) { if(!err) { rows.forEach(function(element) { if (useruid === element.uid) { console.log("[is admin] Found admins!"); return true; } else { console.log("[is admin] User is not admin!"); return false; } }); } else { console.log(err); return false; } }) } ` – HAZZE Aug 10 '21 at 10:06
  • but i don't know why it doesnt return true or false, im recieving output of console.logs but not the return of function (true/false) – HAZZE Aug 10 '21 at 10:07
  • arr... I see it. The return function is a layer below the outer function. – HardcoreGamer Aug 10 '21 at 10:08
  • I edited post, yes i know its layer below the outer function but how can i retrn it? because i need that forEach to check is the user admin or not. – HAZZE Aug 10 '21 at 10:10
  • The solution is much more complex then I anticipated, please see this [article](https://code.tutsplus.com/tutorials/managing-the-asynchronous-nature-of-nodejs--net-36183) for hints – HardcoreGamer Aug 10 '21 at 14:02

1 Answers1

1

As noted the solution is more complicated than you might suspect given the asynchronous nature of Node. There are several ways to address the issue your question presents but I'll include just one here that is relatively flexible and lightweight.

The good news is your function isAdmin and the query it includes can be made much simpler so you'll pick up some lines of code there.

Since you start with a UID and your goal is only to check that it exists in the table, you can use a targeted query and skip all the result looping. This will save time and resources in Node as well as MySQL.

Updated Function Note this is now an async function with a Promise. This way we can later call and await the results. Also the db.query takes an argument for the ? placeholder. We pass it our useruid variable.

const isAdmin = async (useruid) => {
  return new Promise((resolve, reject) => {
    db.query('SELECT uid FROM admins WHERE uid = ?;', useruid, function (error, results, fields) {
      if (error) reject(error);

      // when we get our results we can simply check for length
      // if we have length, there was a match
      // if we have no length, there was no match
      resolve(results.length ? true : false)
    });
  });
};

To call the function… We must wrap in async function if we want to leverage await

(async function(){
  let is_admin = await isAdmin(YOUR_UID_VALUE);
  console.log('is_admin', is_admin);
})();
dusthaines
  • 1,320
  • 1
  • 11
  • 17