孤独プログラマー譚

孤独死が近い。

Promise catch()からthen()への復帰

catch()からthen()へ。
そして、then()からcatch()へ。

const promise = Promise.resolve()

promise
.then(() => {
  console.log(1)
  throw new Error()
})
.catch(() => {
  console.log(2)
  return
})
.then(() => {
  console.log(3)
  throw new Error()
})
.catch(() => {
  console.log(4)
  return
}) // 1 2 3 4


以下のようにも、書き換えられる。

promise
.then(() => {
  console.log(1)
  return Promise.reject(new Error())
})
.catch(() => {
  console.log(2)
  return Promise.resolve()
})
.then(() => {
  console.log(3)
  return Promise.reject(new Error())
})
.catch(() => {
  console.log(4)
  return Promise.resolve()
}) // 1 2 3 4