Skip to content
Advertisement

Using async functions as conditions

Lets say i want to run an if statment where the condition is async function.

const con = require('./con');

if(con.con('email@gmail.com')
  console.log('User exists!')
else {
  console.log('user does not exist?')
}

This is the function, it uses mongoose findOne which is an async task.

const User = require ('../nodeDB/models/user.js');

const con = function (email) {
     User.findOne( { userEmail: email }, function (err, doc) {
       if(err) {
           console.log(err);
       }
       
       if (doc) {
           return false;
       } else {
           return true;
       }
     });
}

module.exports.con = con;

The problem is that the if statment gets called before the con can get executed which then does’nt set the condition.

Advertisement

Answer

You can do it this way :

const con = userEmail => User.findOne({userEmail}).lean().exec();

(async () => {
    if (await con('email@gmail.com')) {
        console.log('User exists!')
    } else {
        console.log('user does not exist?')
    }
})()
  1. Return User.findOne from your function.

(optional) 2. Add it .lean() (returns simple JSON, faster)

(optional) 3. Add it .exec() so it returns a true Promise and not just a thenable

  1. now you can simply await con() anywhere inside an async function, just as if it was synchronous.
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement