JS如何从内部拒绝包装器承诺



如何从一个或内部拒绝包装器承诺?换句话说,如何使数字"3"从不打印?电流输出:

1
2
3

预期输出:

1
2
new Promise(function(resolve, reject) {
console.log(1)
resolve()
})
.then(() => console.log(2))
.then(() => { // how to reject this one if internal fails?
new Promise(function(resolve, reject) {
reject(new Error('Polling failure'));
})
.then(() => console.log(21))
})
.then(() => console.log(3))

看起来您只是缺少了一个return

new Promise(function(resolve, reject) {
console.log(1)
resolve()
})
.then(() => console.log(2))
.then(() => { // how to reject this one if internal fails?
return new Promise(function(resolve, reject) {
reject(new Error('Polling failure'));
})
.then(() => console.log(21))
})
.then(() => console.log(3))

为了拒绝来自.then()处理程序的承诺链,您需要:

使用throw

抛出任何值都会将承诺标记为不成功:

const p = new Promise(function(resolve, reject) {
console.log(1)
resolve()
})
.then(() => console.log(2))
.then(() => { throw new Error(); })
.then(() => console.log(3));

p
.then(() => console.log("sucessful finish"))
.catch(() => console.log("error finish"));

返回被拒绝的承诺

最简单的方法是使用Promise.reject:

const p = new Promise(function(resolve, reject) {
console.log(1)
resolve()
})
.then(() => console.log(2))
.then(() => Promise.reject("problem"))
.then(() => console.log(3));

p
.then(() => console.log("sucessful finish"))
.catch(() => console.log("error finish"));

最新更新