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

JS how to reject wrapper promise from inside one?

如何从一个或内部拒绝包装承诺?换句话说,如何让数字“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"));

Return 一个被拒绝的承诺

最简单的方法是 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"));