如果顺序不正确,为什么 Promise.catch() 也会调用 .then() ?

Try*_*ria 4 javascript

我想知道为什么下面的 Promise 都调用 catch() 和 then() 方法。

function testpromise(){
  return new Promise((resolve, reject)=>{
    reject("Error");
  })
}


testpromise()
.catch((err)=>{console.log(err)})
.then(()=>{console.log("Then")})
Run Code Online (Sandbox Code Playgroud)

但为什么这个不呢?(我只将 .then() 方法移到 .catch() 方法之前)。

function testpromise(){
  return new Promise((resolve, reject)=>{
    reject("Error");
  })
}


testpromise()
.then(()=>{console.log("Then")})
.catch((err)=>{console.log(err)})
Run Code Online (Sandbox Code Playgroud)

这是一个错误吗?有点奇怪,我无法在 .then() 之前获取 catch() 方法。对我来说,在 then 之前放置 catch 可以让我快速检查是否正确处理可能的错误。我有几十个像这样写的承诺,我刚刚注意到它也会立即调用我的 .then() 方法,这不好。

cha*_*tfl 6

catch 返回一个承诺,因此除非您抛出或返回另一个被拒绝的承诺,否则它将解析为链中的下一个 then()

以下人为的示例应该可以帮助您形象化它

testpromise()
  .catch((err) => {
    console.log('First catch=', err)
    return 'Catch message'; // implicit return value, with no return next then receives undefined
  })
  .then((fromCatch) => {
    console.log("from first catch =", fromCatch)
  })
  .then(testpromise) // return another rejected promise to next catch
  .then(() => console.log('Not called'))
  .catch((err) => {
    console.log('Second catch');
    throw 'New Error'
  })
  .then(() => console.log('Not called #2'))
  .then(() => console.log('Not called #3'))
  .catch(err => console.log('Final catch =', err))

function testpromise() {
  return new Promise((resolve, reject) => {
    reject("Error");
  })
}
Run Code Online (Sandbox Code Playgroud)