在面試過程中,要求實現(xiàn)promise贞岭。如果你能實現(xiàn)出一個簡易版的Promise 既可以過關(guān)了
// 創(chuàng)建三個常量用于表示狀態(tài)
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
function MyPromise(fn) {
const that = this
that.state = PENDING
that.value = null // 保存resolve 或者 reject中傳入的值
// 用于保存then中的回調(diào) 當執(zhí)行完promise狀態(tài)可能還是等待中搓侄,需要把then中的回調(diào)保存
that.resolvedCallbacks = []
that.rejectedCallbacks = []
function resolve(value) {
if (that.state === PENDING){
that.state = RESOLVED
that.value = value
that.resolvedCallbacks.map(cb=>cb(this.value))
}
}
function reject(value) {
if (that.state === PENDING){
that.state = REJECTED
that.value = value
that.rejectedCallbacks.map(cb=>cb(that.value))
}
}
}
MyPromise.prototype.then = function (onFulfilled,onRejected) {
const that = this
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled: v=>v
onRejected = typeof onRejected === 'function' ? onRejected : v=>v
if (that.state === PENDING){
that.resolvedCallbacks.push(onFulfilled)
that.rejectedCallbacks.push(onRejected)
}
if (that.state === RESOLVED){
onFulfilled(that.value)
}
if (that.state === REJECTED){
onRejected(that.value)
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者