-2

The below code is to get due amount by subtracting actual fee with amount paid. I get value returned as null instead of difference. WHen i add return for db.XXX.findOne, I get error as "Invalid value Promise". Please help me understand where i went wrong

let x=getDueAmount(1,200);

const getDueAmount = (id,amountpaid) => {
  let due;
  db.XXX.findOne({
    where:{id: id},
    attributes:['fees']
   }).then(feeDetail=>{
      due=feeDetail.fees-amountpaid;
       });
   return due;
}
Gayathri
  • 1,776
  • 5
  • 23
  • 50
  • Asynchronous functions have to stay asynchronous the whole way down. Return a Promise from this function, not `due` because it will not be populated in time. – zero298 Feb 05 '18 at 18:43
  • 1
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – zero298 Feb 05 '18 at 18:44

1 Answers1

0

Simply return from your promise (your Db call). In your code your returning the value of due prior to the result coming back from the db. Read up on promises and asynchronous javascript

let x=getDueAmount(1,200);

const getDueAmount = (id,amountpaid) => {
  return db.XXX.findOne({
    where:{id: id},
    attributes:['fees']
   }).then(feeDetail=>{
     return feeDetail.fees-amountpaid;
   });
}
Michael McCabe
  • 1,132
  • 8
  • 12
  • As already said in question comments, I tried the same you mentioned and i got "Invalid Data Promise". To mention, the value i receive here would be assigned to an object which is part of result of another sequelize query. I ain't sure if it is expected in such a scenario – Gayathri Feb 06 '18 at 12:04
  • No, the code you showed returned due outside of the promise. Have you tried my exact code? If you want to use the returned value in another query, then it needs to be along the chain. I can only assume from the code in your question that you don’t understand promises/asynchronous code – Michael McCabe Feb 06 '18 at 12:11