Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Firstly your con() function doesn't return anything. You will need to return User.findOne(....)

Your if statement needs to respect the fact that the async task has to complete first.

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

Or with aynsc/await:

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

about 4 years ago · Juan Pablo Isaza Relatório

0

Use await or put your logic in then block.

// must be in async declared function
if (await foo()) {
}
else {
}

// or 

foo().then(res=>{
  if (res) {
  }
  else {
  }
})
about 4 years ago · Juan Pablo Isaza Relatório

0

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.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda