你能返回一个带有预定义的finally的Promise吗?

DaD*_*aDo 5 javascript promise

我有一个返回 Promise 的函数。.then()当我在or块中使用完 Promise 后.catch(),我总是想执行相同的清理代码。我当前的设置是这样的:

const promiseWithFinally = () => {
  return new Promise((resolve, reject) => {
    // resolve or reject at some point
  }).finally(() => console.log('finally done'))
}

promiseWithFinally()
  .then(() => console.log('then done'))
  .catch(() => console.log('catch done'))
Run Code Online (Sandbox Code Playgroud)

我想要发生的是要么then donecatch done登录,然后再登录finally done。然而,它似乎以完全相反的顺序执行 - 当我在 5 秒超时后解析 Promise 时,finally done首先在 5 秒后记录,然后then done立即记录。

我做错了什么或者一般可以这样做吗?我知道我可以将 附加.finally()到每个单独的函数调用中,但由于它总是相同的,所以我想将它放在函数定义中。

mar*_*lin 1

不,这是不可能的。最后是为了在给定的承诺之后进行清理,而不是为了它thencatch方法。

您可以做的是将thencatch方法传递给将附加在之前的函数finally

const promiseWithFinally = (chain) => {
  return new Promise((resolve, reject) => {
    // resolve or reject at some point
    setTimeout(resolve, 1000);
  }).then(chain.then, chain.catch).finally(() => console.log('finally done'))
}

promiseWithFinally({
  then: () => console.log('then done'),
  catch: () => console.log('catch done')
})
Run Code Online (Sandbox Code Playgroud)