finally方法实现:finally方法不管成功还是失败都会执行。
// 定义状态
const STATUS_PENDING = 'pending'
const STATUS_FULFILLED = 'fulfilled'
const STATUS_REJECTED = 'rejected'
// 工具函数
function executeTryCatchError(execFn, value, resolve, reject) {
try {
const result = execFn(value)
resolve(result)
} catch (err) {
reject(err)
}
}
class TPromise {
constructor(execute) {
this.status = STATUS_PENDING
this.value = undefined
this.reason = undefined
this.onFulfilledFns = []
this.onRejectedFns = []
const resolve = (value) => {
if (this.status === STATUS_PENDING) {
queueMicrotask(() => {
if (this.status !== STATUS_PENDING) return
this.status = STATUS_FULFILLED
this.value = value
this.onFulfilledFns.forEach(fn => {
fn()
})
})
}
}
const reject = (reason) => {
if (this.status === STATUS_PENDING) {
queueMicrotask(() => {
if (this.status !== STATUS_PENDING) return
this.status = STATUS_REJECTED
this.reason = reason
this.onRejectedFns.forEach(fn => {
fn()
})
})
}
}
execute(resolve, reject)
}
then(onFulfilled, onRejected) {
onRejected = onRejected || (err => {throw err})
// 处理catch无值,无法调用finally
onFulfilled = onFulfilled || (value => {return value})
return new TPromise((resolve, reject) => {
if (this.status === STATUS_FULFILLED && onFulfilled) {
executeTryCatchError(onFulfilled, this.value, resolve, reject)
}
if (this.status === STATUS_REJECTED && onRejected) {
executeTryCatchError(onRejected, this.reason, resolve, reject)
}
if (this.status === STATUS_PENDING) {
onFulfilled && this.onFulfilledFns.push(() => {
executeTryCatchError(onFulfilled, this.value, resolve, reject)
})
onRejected && this.onRejectedFns.push(() => {
executeTryCatchError(onRejected, this.reason, resolve, reject)
})
}
})
}
catch(onRejected) {
return this.then(undefined, onRejected)
}
// finally方法实现
finally(onFinally) {
this.then(() => {
onFinally()
}, () => {
onFinally()
})
}
}
let promise = new TPromise((resolve, reject) => {
console.log('pending状态')
// resolve('aaaa')
reject('bbb')
})
promise.then(res => {
console.log('res1:'+res)
return 111
}).catch(err => {
console.log('catch:'+err)
}).finally(() => {
console.log('finally')
})
零前端学习输出,一起探讨,一起进步。
留言与评论(共有 0 条评论) “” |