# ❓ 模拟实现一个 Promise.finally

# Promise.prototype.finally()

finally() 方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。该方法是 ES2018 引入标准的。

promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
1
2
3
4

上面代码中,不管 promise 最后的状态,在执行完 thencatch 指定的回调函数以后,都会执行 finally 方法指定的回调函数。

finally 方法的回调函数不接受任何参数,这意味着没有办法知道,前面的 Promise 状态到底是 fulfilled 还是 rejected。这表明,finally 方法里面的操作,应该是与状态无关的,不依赖于 Promise 的执行结果。

finally 本质上是 then 方法的特例。

promise.finally(() => {
  // 语句
})

// 等同于
promise.then(
  (result) => {
    // 语句
    return result
  },
  (error) => {
    // 语句
    throw error
  }
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 具体实现

Promise.prototype.finally = function (callback) {
  let P = this.constructor
  return this.then(
    (value) => P.resolve(callback()).then(() => value),
    (reason) =>
      P.resolve(callback()).then(() => {
        throw reason
      })
  )
}
1
2
3
4
5
6
7
8
9
10

Promise.prototype.finally