0

I am trying to copy to a local variable the data of a successfully saved user on monogodb yet not successful.

I initialized a variable called regiseredUser and on the promise function of .save().then(//promise) I tried to save the returned data to regiseredUser regiseredUser = user; however when I console.log(regiseredUser) I am getting empty object

 let regiseredUser = {}
  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      return res.status(400).json({ email: "Email already exists" });
    } else {
      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password,
        verified: req.body.verified,
      });
      newUser.verified = false;

      // Hash password before saving in database
      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
          newUser
            .save()
            .then((user) => {
              regiseredUser = user;

              res.json(user)}

              )
            .catch(err => console.log(err));
        });
      });
      console.log(regiseredUser)

I was expecting user to be copied to regiseredUser yet it is not happening

moytoy
  • 7
  • 3
  • I don't understand what you want to do, you're missing a few bracket closures in your code. It's like you understand promises but you don't. You said you want to call a function instead of res.json(), you can do that. Just don't try to access the variable before the promise is resolved with it. Or use await and make your current function asynchronous. – Zee May 20 '19 at 00:56

1 Answers1

0

This isn't possible. Because promises are waiting for an action to be completed, the rest of the code after the promise is executed before the actual code inside the promise is. You'll instead have to process everything in the last promise or have a function process everything and then call a callback function.

For more information on how promises work, check out the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

brian
  • 41
  • 5
  • is there a better way for executing a function once user has successfully being saved in database – moytoy May 19 '19 at 21:33
  • like instead of res.json I would like to call a function – moytoy May 19 '19 at 21:33
  • Nope, you just put it inside of the promise after you get the data. If you're going to use this function a lot, I'd recommend creating a function with a callback parameter and then calling it once you've received the data. – brian May 19 '19 at 21:36