我有以下应许链:
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
我的诺言。我在这里做错了什么?
答案 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"
});