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

时间:2021-01-28 17:03:19

标签: javascript es6-promise

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

2 个答案:

答案 0 :(得分:2)

看起来您只是缺少一个 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))

答案 1 :(得分:1)

为了拒绝来自 .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"));

相关问题