手写实现简版Promise
class myPromise {
constructor(exector) {
this.status = PROMISE_STATUS_PENDING
this.value = null
this.reason = null
this.onFulfilledfns = []
this.onRejectedfns = []
const resolve = value => {
if (this.status === PROMISE_STATUS_PENDING) {
this.value = value
queueMicrotask(() => {
this.status = PROMISE_STATUS_FULFILLED
this.onFulfilledfns.forEach(fn => {
fn()
})
})
}
}
const reject = reason => {
if (this.status === PROMISE_STATUS_PENDING) {
this.status = PROMISE_STATUS_REJECTED
this.reason = reason
queueMicrotask(() => {
this.onRejectedfns.forEach(fn => {
fn()
})
})
}
}
try {
exector(resolve, reject)
} catch (err) {
console.log(err)
}
}
then(onFulFilled, onRejected) {
const defaultRejected = err => err
if (!onRejected) {
onRejected = defaultRejected
}
return new myPromise((resolve, reject) => {
if (this.status === PROMISE_STATUS_FULFILLED && onFulFilled) {
execFunctionWithCatchError(onFulFilled, this.value, resolve, reject)
}
if (this.status === PROMISE_STATUS_REJECTED && onRejected) {
execFunctionWithCatchError(onRejected, this.reason, resolve, reject)
}
if (this.status === PROMISE_STATUS_PENDING) {
if (onFulFilled) {
this.onFulfilledfns.push(() => {
execFunctionWithCatchError(onFulFilled, this.value, resolve, reject)
})
}
if (onRejected) {
this.onRejectedfns.push(() => {
execFunctionWithCatchError(onRejected, this.reason, resolve, reject)
})
}
}
})
}
catch(onRejected) {
return this.then(undefined, onRejected)
}
}
function execFunctionWithCatchError(fn, v, resolve, reject) {
try {
const res = fn(v)
resolve(res)
} catch (err) {
reject(err)
}
}
const p = new myPromise((resolve, reject) => {
resolve('123')
})
p.then(res => {
console.log(res)
})
p.then(res => {
console.log(res)
})
p.then(res => {
console.log(res)
})
setTimeout(() => {
p.then(res => {
console.log('------', res)
})
}, 1000)