0

I tried to make async and await function in mongoose. but in one case it simply didn't work while in another case it shows syntax error.

here is my code

exports.updateDiscount= async (_id,discount) =>
{
    try
    {
        console.log(_id,discount);
        Discount.findOne({_id},(err,user) =>
        {
            if(user)
            {
              user.discountRate=parseFloat(discount);
              let saveUser= await user.save();
              if(saveUser)
              {
                  console.log("Discount saved");
                  return true
              }
            }
        })
    } catch(err)
    {
        console.log(err);
    }
}

I am using the thing function in another module


if( updateDiscount(item.userid,discount) === true)
   {
   }

2
  • 2
    const user = await Discount.findOne({_id}) ? Commented Dec 16, 2020 at 12:40
  • What error exactly? Commented Dec 16, 2020 at 12:45

2 Answers 2

2

Solution ::

exports.updateDiscount= async (_id,discount) =>
{
    try
    {
        console.log(_id,discount);
        let user = await Discount.findOne({_id});
        
            if(!!user)
            {
              user.discountRate=parseFloat(discount);
              let saveUser= await user.save();
              if(!!saveUser)
              {
                  console.log("Discount saved");
                  return true
              }
            }
    } catch(err)
    {
        console.log(err);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

you need to await the function

const answer = await updateDiscount(item.userid,discount);
if(answer) {
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.