arash koohnavard
arash koohnavard

Reputation: 23

having problem with Node.js and ES6 promise

this is my piece of code:

i declared a variable(newSeller) and i expect to use it in the process

    let newSeller = '';
    if (req.body.selectSeller == '') {
        User.findOne({email: req.body.sellerEmail}).then(userEx => {
            if (!userEx) {
                const newUser = new User({
                    firstName: req.body.sellerName,
                    lastName: req.body.sellerLastName,
                    title: req.body.sellerTitle,
                    phoneNumber: req.body.sellerPhNum,
                    email: req.body.sellerEmail,
                    password: req.body.password,
                    address: req.body.sellerAddress
                });
                bcrypt.genSalt(10, (err, salt)=>{
                    bcrypt.hash(newUser.password, salt, (err, hash)=>{
                        newUser.password = hash;

                    });
                });
                newUser.save().then(savedSeller => {
                    newSeller = savedSeller.id;
                });

            } else if (userEx) {
                req.flash('error_message', 'this email already exists. try another one')
                res.redirect('/admin/invoice/incoming');
            }
        });

    } else {
        newSeller = req.body.selectSeller;
    }

this piece of code actually saves the expected document successfully but when i assign the variable (newSeller) to the value of ES6 promise (after then() ) it doesn't work! could you please help me with this?

how can i fetch the saved user values?

Upvotes: 0

Views: 51

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

Basically you are using async and sync functions together in various places which messes up everything. Basically you cannot use sync functions if you use even one async function in the entire module. But then again in async functions, Try to use promise based syntaxes or async-await Assuming you are using the code in some express route here is how you can simplify the code(commented for understanding):

app.post('/someroute', async (req, res) => { //<<-Async handler
  let newSeller = '';
  if (req.body.selectSeller == '') {
    try { //<<--need to catch `async-await` errors
      const userEx = await User.findOne({ email: req.body.sellerEmail });//<<awaiting the result
      if (!userEx) {
        const newUser = new User({
          firstName: req.body.sellerName,
          lastName: req.body.sellerLastName,
          title: req.body.sellerTitle,
          phoneNumber: req.body.sellerPhNum,
          email: req.body.sellerEmail,
          password: req.body.password,
          address: req.body.sellerAddress
        });
        const salt = await bcrypt.genSalt(10); // await 
        const hash = await bcrypt.hash(newUser.password, salt);// await
        newUser.password = hash;
        const savedSeller = await newUser.save(); //await
        newSeller = savedSeller.id;
      } else {
        req.flash('error_message', 'this email already exists. try another one')
        res.redirect('/admin/invoice/incoming');
      }
    } catch (err) { //<<--if there is an error
      req.flash(...something...)
      res.redirect(...somewhere...);
    }
  } else {
    newSeller = req.body.selectSeller;
  }
  //do something with newSeller
})

Upvotes: 1

Related Questions