在面试过程中,要求实现promise。如果你能实现出一个简易版的Promise 既可以过关了
// 创建三个常量用于表示状态
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
function MyPromise(fn) {
const that = this
that.state = PENDING
that.value = null // 保存resolve 或者 reject中传入的值
// 用于保存then中的回调 当执行完promise状态可能还是等待中,需要把then中的回调保存
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)
}
}