Richard
Richard

Reputation: 7433

Promise rejected "reject is not defined" in my chain of Promises

I have the following chain of Promises:

let promise         = new Promise((resolve, reject) => {
    imgToDisplay.onload = () => {
        resolve(imgToDisplay.width);
    }
})
.then((result) => {
    window.URL.revokeObjectURL(imgToDisplay.src);
    if (result >= 20)
        reject('Image width too large');
})
.then(() => {   
    //I do something with the image file here if it is not rejected
})
.catch((e) => {
    alert(e.message); //This happened, however "reject is not defined"
});

I did not reject nor resolve my Promise in the second then(). What did I do wrong here?

Upvotes: 0

Views: 1867

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 371138

Unless you're directly inside the Promise constructor, you can't call reject, because it's not in scope. But, if you throw an error inside the .then, you can force the control flow to go to the next .catch in the chain (skipping .thens in between):

let promise         = new Promise((resolve, reject) => {
  imgToDisplay.onload = () => {
    resolve(imgToDisplay.width);
  }
})
.then((result) => {
  window.URL.revokeObjectURL(imgToDisplay.src);
  if (result >= 20)
    // This will result in the Promise being rejected:
    throw new Error('Image width too large');
})
.then(() => {   
  //I do something with the image file here if it is not rejected
})
.catch((e) => {
  alert(e.message); //This happened, however "reject is not defined"
});

In this case though, since the test that results in the rejected Promise can be done in the Promise constructor, you could call reject in the constructor instead, if you wanted:

let promise         = new Promise((resolve, reject) => {
  imgToDisplay.onload = () => {
    if (imgToDisplay.width >= 20) {
      reject('Image width too large');
    }
    resolve(imgToDisplay.width);
  }
})

Upvotes: 2

Shridhar Sharma
Shridhar Sharma

Reputation: 2385

Use throw instead of reject in then callback

let promise         = new Promise((resolve, reject) => {
    imgToDisplay.onload = () => {
        resolve(imgToDisplay.width);
    }
})
.then((result) => {
    window.URL.revokeObjectURL(imgToDisplay.src);
    if (result >= 20)
        throw 'Image width too large';
})
.then(() => {   
    //I do something with the image file here if it is not rejected
})
.catch((e) => {
    alert(e.message); //This happened, however "reject is not defined"
});

Upvotes: 0

Related Questions