简体   繁体   中英

promise function in node can't get the return value

I am trying to get the return value from the below function, but I can't because return value gets executed before the result being returned.

Could someone point me to the right direction?

exports.addUser = async (data) => {

  const updateduser = await db.User.findOne({
    where: {
      email: data.email,
    },
  }).then(user => {
    if (user) {
      return null
    } else {
      bcrypt.hash(data.password, 10).then(
        hashedPassword => {
          const newUser = {
            firstName: data.firstName,
            lastName: data.lastName,
            email: data.email,
            password: hashedPassword
          }
          db.User.create(newUser).then(insertedUser => {
            return insertedUser
          })
        }
      )
    }
  });

  return updateduser
}

The controller where response should be based on the returned value from addUser functions above..

exports.signUp = async (req, res, next) => {
  const userData = {
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    email: req.body.email,
    password: req.body.password,
  };

  const {
    error
  } = signUpValidation(userData);
  if (error) return res.status(400).json({
    message: error.details[0].message
  });
  try {
    const user = await addUser(userData);
    if (!user) {
      res
        .status(403)
        .json({
          message: "This email is already exits, Please login 🔁 "
        });
    } else {
      res.status(200).json({
        id: user.id,
        email: user.email,
        status: true,
        message: " You're now registered!✅Please check your Email!✅  ",
      });
    }
  } catch (error) {
    next(error);
  }
}

You are mixing async/await, then, and nested then calls to a point where it gets really hard to follow your code. You should always try to stick to either async/await or then's (there are a couple of exceptions, though). Also try to avoid nesting whenever possible. Your code can be simplified to the following:

exports.addUser = async (data) => {
  const user = await db.User.findOne({
    where: {
      email: data.email,
    },
  });
  if (user) {
    return null;
  }
  const hashedPassword = await bcrypt.hash(data.password, 10);
  const newUser = {
    firstName: data.firstName,
    lastName: data.lastName,
    email: data.email,
    password: hashedPassword,
  };
  return db.User.create(newUser);
};

You should probably read a little more about await .

Note that the main problem in your code is that you are returning something in a nested then callback. But you neither return the inner nor outer then block itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM