简体   繁体   中英

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?

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 .then s 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);
  }
})

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"
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM