Anna Klein
Anna Klein

Reputation: 2171

Issue with promise: ReferenceError: reject is not defined

I am working with some own built promise examples to understand how this function is working.

That following code produces the error

ReferenceError: reject is not defined

I start this with node Promise.js and use node version 8.11.3

Here is my code, the part which produces the error is commented with "problem

function testPromise () {

//part 1
  function checkCountOnServer () {
    return new Promise(function (resolve, reject) {
      var available = false
      if (available) {
        resolve('available')
      }
      else {
        reject('not available')
      }
    })
  }

  function checkPayment () {
    return new Promise(function (resolve, reject) {
      var booleanTest = true
      if (booleanTest) {
        resolve('payment done')
      }
      else {
        reject('no payment received')
      }
    })
  }

  var checkCountOnServerVar = checkCountOnServer()
  checkCountOnServerVar.then(function (resolve) {
    console.log(resolve)
    return resolve(checkPayment())
  }, function (reason) {
    console.log(reason) //works
    reject(reason) // problem
  }).then(function (value) { console.log(value) },
    function (rejected) {
      console.log(rejected) //problem
    })

}

testPromise()

I actually expect the message 'not available' two times.

Even if I change reject(reason) to reject('test') I get the same error.

Help me please.

Upvotes: 5

Views: 18698

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138497

 checkCountOnServerVar.then(function (resolve) {

The then callback is called with whatever value the promise was resolved to, which is "payment done" in your case,and that is not a function, so you can't call it. To chain a promise from inside a then handler, just return it:

checkCountOnServerVar.then(function (status) {
 console.log(status);
 return checkPayment();
})

Additionally your error catcher does not make sense at all,

function (reason) {
  console.log(reason) //works
  reject(reason) // problem
}

As reject is not defined, and as you actually don't handle the error. If you don't handle the error, there is no sense in attaching a handler, otherwise you should return a value the chain can continue with, such as:

function(error) {
  console.error("Something bad happened", error);
  return "An error occured, but we don't mind...";
}

To sum up:

checkCountOnServer()
  .then(serverCount => checkPayment())
  .then(payment => console.log(payment))
  .catch(error => console.error(error));

Upvotes: 6

Related Questions