在我的承诺链中,承诺拒绝“未定义拒绝”

时间:2019-05-04 07:46:51

标签: javascript promise es6-promise

我有以下应许链:

h3

在第二个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" }); 中,我既没有reject也没有resolve我的诺言。我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

除非您直接位于Promise构造器内部,否则就无法调用reject,因为它不在范围内。但是,如果在.then内抛出错误,则可以强制控制流转到链中的下一个.catch(在这之间跳过.then):

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

在这种情况下,由于可以在Promise构造函数中完成导致拒绝Promise的测试,因此,如果需要,您可以在构造函数中调用reject:< / p>

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

答案 1 :(得分:0)

使用throw代替在then回调中拒绝

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