0

I want to return true or false to a app.locals function in EJS but, it returns nothing, return is not working. Here is my code:

  app.locals.isAdmin = async(uidd) => {
    var check = await Admins.find({
       userID: [uidd]
    }).then(result => {
      var result = result.toString();
      if(result !== ""){
        console.log("Is admin")
        return true;
      }else{
        console.log("Is not admin")
        return false;
      }
    })
  };

1 Answers1

0

Answer

Since you are using an async function await is in charge of unwrap your promise, for that reason, you no longer need to call .then(). I recommend to use the following code.

Code

app.locals.isAdmin = async(uidd) => {
  var result = await Admins.find({
     userID: [uidd]
  });

  var check = checkAdmin(result.toString());
  return check;
};

function checkAdmin(value) {
  if(value !== ""){
    console.log("Is admin")
    return true;
  }

  console.log("Is not admin")
  return false;
}

Reference

Async function

Jose Vasquez
  • 1,678
  • 1
  • 6
  • 14
  • This is not working... It gives me this log: Promise { } before sending Is not admin or Is admin – Jaqueline Québec Sep 07 '20 at 15:56
  • Where is app.locals.isAdmin being called? – Jose Vasquez Sep 07 '20 at 15:59
  • app.locals.isAdmin is called: isAdmin in header.ejs and the function app.locals.isAdmin in dashboard.js (app is defined in dashboard.js) – Jaqueline Québec Sep 07 '20 at 16:02
  • The thing is. All the async functions return a Promise. If you explicitly call isAdmin function you have to make use of **app.locals.isAdmin(uidd).then(check => {...}); ** In order to unwrap your data. Otherwise you only get the Promise as you mentioned in your previous comment. – Jose Vasquez Sep 07 '20 at 16:07
  • I dont understand what you mean in **If you explicitly call isAdmin function you have to make use of **app.locals.isAdmin(uidd).then(check => {...}); ** In order to unwrap your data** – Jaqueline Québec Sep 07 '20 at 16:14
  • 1
    Take a look into this [post](https://stackoverflow.com/questions/60203249/ejs-async-true-with-node-express), probably you have to add the async option before rendering. – Jose Vasquez Sep 08 '20 at 13:29