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

164
Visualizações
How to add async/await in function login nodejs?

I just learned Nodejs, now I'm having a problem that I don't know how to add async/await in function service login. I researched today without finding a solution. Please help me. Thank you very much!

userService.js

exports.findUser = async (email, password) => {
  var result = null;
  User.findOne({
    email: email,
    password: password,
  })
    .then((data) => {
      if (data) {
        result = data;
      }
    })
    .catch((err) => {});
  return result;
};

userController.js

exports.login = (req, res, next) => {
  var email = req.body.email;
  var password = req.body.password;

  var data = userService.findUser(email, password);

  console.log(data);

  if (data !== null) {
    res.status(200).json({ message: "null" });
  } else {
    res.status(401).json({ message: "Incorrect email or password!" });
  }
};
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Solution

From userService.js it is clear you are using mongoose. to use async and await in nodejs you can edit your code like this...

exports.findUser = async (email, password) => {
    try{
        var result = await User.findOne({
        email: email,
        password: password,
       })
       return result
    }catch(e){
      // catch errors and do something
   }
}

Notice i used try and catch block so that i can catch error if anything goes wrong in the await. after the await resolves you get back a mongodb document same as you will get in the parameter passed to .then in a promise callback function.

about 4 years ago · Juan Pablo Isaza Relatório

0

The thing with async functions is it allows you to await a promise, basicallly suspending the execution of the function until the promise resolves. So, your code could be rewritten as:

//userService.js
exports.findUser = async (email, password) => {
  var result = null;
  try{
     result = await User.findOne({
       email: email,
       password: password,
     })
  } catch(e){
     \\handle error
  }
  return result;
};
//userController.js
exports.login = async (req, res, next) => {
  var email = req.body.email;
  var password = req.body.password;

  var data = await userService.findUser(email, password);

  console.log(data);

  if (data !== null) {
    res.status(200).json({ message: "null" });
  } else {
    res.status(401).json({ message: "Email hoặc mật khẩu không đúng!" });
  }
};

By making both functions async, you can take advantage of the await keyword and promises without the 'callback hell' that appears with .then() and .catch() on promises. MDN Docs

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