Promise.prototype.finally 的作用,如何自己實現(xiàn) Promise.prototype.finally
本文轉(zhuǎn)載自微信公眾號「三分鐘學(xué)前端」,作者sisterAn。轉(zhuǎn)載本文請聯(lián)系三分鐘學(xué)前端公眾號。
Promise.prototype.finally() 的作用
Promise.prototype.finally() 是 ES2018 新增的特性,它回一個 Promise ,在 promise 結(jié)束時,無論 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 沒有參數(shù)
- finally 會將結(jié)果和 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 對象最后狀態(tài)如何,都會執(zhí)行的操作
- 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
- })
- })
- }
來自:https://github.com/sisterAn/blog