Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda