# 实现Promise.finally()
// 方法1
Promise.prototype.finally = function (cb) {
let P = this.constructor
return this.then(
value => P.resolve(cb()).then(() => value),
reason => P.resolve(cb()).then(() => { throw reason })
)
}
// 方法2
window.Promise && !('finally' in Promise) && !function() {
Promise.prototype.finally = function(cb) {
cb = typeof cb === 'function' ? cb : function() {}
// 获取当前实例构造函数的引用
let Fn = this.constructor
// 接受状态:返回数据
let onFulfilled = function(data) {
return Fn.resolve(cb()).then(function() {
return data
})
}
// 拒绝状态:抛出错误
let onRejected = function(err) {
return Fn.resolve(cb()).then(function() {
throw err
})
}
return this.then(onFulfilled, onRejected)
}
}()