Home > Blockchain >  Promise can't complete the calculation
Promise can't complete the calculation

Time:02-18

I have a pretty easy formula which does not work inside Promise. Problem is following - whatever I put for parameters a and b, I always get failure, even though its clearly more thank 0. I am pretty sure that I am missing something but I can't understand what exactly, because with other formula it works (maybe I cannot call the function inside the Promise? in that case what would be the other way?). Sorry for noob question, Im new to it

const pidr = new Promise((resolve, reject) => {

    const result = (a, b) => (a   b) ** 2
    result(5, 6)

    if (result > 0) {
      resolve()
    } else {
      reject()
    }
  })

  .then(() => console.log('Success'))
  .catch(() => console.error('Failure'))

CodePudding user response:

You need to create variable and set result of function execution. See below:

  const pidr = new Promise((resolve, reject) => {

    const result = (a, b) => (a   b) ** 2

    const res = result(5, 6)

    if (res > 0) {
      resolve()
    } else {
      reject()
    }
  })

  .then(() => console.log('Success'))
  .catch(() => console.error('Failure'))

CodePudding user response:

This:

result(5, 6);

calls the function, but does not save the returned value. You then compare result (which is a function) to 0, and that doesn't make sense.

Instead:

const answer = result(5, 6);

if (answer > 0) {
  resolve()
} else {
  reject()
}

CodePudding user response:

result is a function and it doesn't have to be, but if you want it to be a function you can call it inside of your if, like so:

const pidr = new Promise((resolve, reject) => {

    const result = (a, b) => (a   b) ** 2

    if (result(5, 6) > 0) {
      resolve()
    } else {
      reject()
    }
  })

  .then(() => console.log('Success'))
  .catch(() => console.error('Failure'))
  • Related