Home > Back-end >  How to add async/await in function login nodejs?
How to add async/await in function login nodejs?

Time:12-07

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: "Email hoặc mật khẩu không đúng!" });
  }
};

CodePudding user response:

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.

CodePudding user response:

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

  • Related