Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promise.prototype.finally 的作用,如何自己实现 Promise.prototype.finally #95

Open
sisterAn opened this issue Apr 28, 2021 · 0 comments

Comments

@sisterAn
Copy link
Owner

Promise.prototype.finally() 的作用

Promise.prototype.finally() 是 ES2018 新增的特性,它回一个 Promise ,在 promise 结束时,无论 Promise 运行成功还是失败,都会运行 finally ,类似于我们常用的  try {...} catch {...} finally {...}

Promise.prototype.finally() 避免了同样的语句需要在 then()catch() 中各写一次的情况

new Promise((resolve, reject) => {
  setTimeout(() => resolve("result"), 2000)
})
  .then(result => console.log(result))
  .finally(() => console.log("Promise end"))

// result
// Promise end

reject :

new Promise((resolve, reject) => {
  throw new Error("error")
})
  .catch(err => console.log(err))
  .finally(() => console.log("Promise end"))

// Error: error
// Promise end

注意:

  • finally 没有参数
  • finally 会将结果和 error 传递
new Promise((resolve, reject) => {
  setTimeout(() => resolve("result"), 2000)
})
  .finally(() => console.log("Promise ready"))
  .then(result => console.log(result))

// Promise ready
// result

手写一个 Promise.prototype.finally()

不管 Promise 对象最后状态如何,都会执行的操作

MyPromise.prototype.finally = function (cb) {
  return this.then(function (value) {
    return MyPromise.resolve(cb()).then(function () {
      return value
    })
  }, function (err) {
    return MyPromise.resolve(cb()).then(function () {
      throw err
    })
  })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant