手写promise
前言
我这里准备收录面试题经常问的一些手写题,js中es6面试经常的,希望对大家有所帮助,共同进步。目前只写了Promise的实现,后续还会更新。
Promise的实现
class Promise {
constructor(FC) {
this.status = 'padding'
this.result = null
this.resolveCallvacks = []
this.rejectCallvacks = []
try {
FC(this.resolve.bind(this), this.reject.bind(this))
} catch (error) {
this.reject(error)
}
}
then(onFULFILLED, onREJECTED) {
onFULFILLED = typeof onFULFILLED === 'function' ? onFULFILLED : () => { }
onREJECTED = typeof onREJECTED === 'function' ? onREJECTED : () => { }
if (this.status == 'succes') {
setTimeout(() => {
onFULFILLED(this.result)
})
}
if (this.status == 'error') {
setTimeout(() => {
onREJECTED(this.result)
})
}
if (this.status == 'padding') {
this.resolveCallvacks.push(onFULFILLED)
this.rejectCallvacks.push(onREJECTED)
}
return new Promise((onFULFILLED, onREJECTED) => {
onFULFILLED = typeof onFULFILLED === 'function' ? onFULFILLED : () => { }
onREJECTED = typeof onREJECTED === 'function' ? onREJECTED : () => { }
if (this.status == 'succes') {
setTimeout(() => {
onFULFILLED(this.result)
})
}
if (this.status == 'error') {
setTimeout(() => {
onREJECTED(this.result)
})
}
if (this.status == 'padding') {
setTimeout(() => {
this.resolveCallvacks.push(onFULFILLED)
this.rejectCallvacks.push(onREJECTED)
})
}
})
}
resolve() {
setTimeout(() => {
if (this.status == 'padding') {
this.status = 'success'
this.result = result
this.onResolvedCallbacks.forEach(callback => {
callback(result)
});
}
});
}
reject(result) {
setTimeout(() => {
if (this.status == 'padding') {
this.status = 'error'
this.result = result
this.onRejectedCallbacks.forEach(callback => {
callback(result)
});
}
});
}
}