//手写promise
const FULFILLDE = 'fulfilled'
const PENDING = 'pending'
const REJECTED = 'rejected'
class myPromise {
constructor (fn) {
this.value = null
this.state = 'pendng'
this.reason = null
this.onResolveCallBacks = []
this.onRejectedCallBacks = []
const resolve = (cb) => {
setTimeout(() => {
if (this.state === PENDING) {
this.state = FULFILLDE
this.onFulfilledCallbacks.map(cb => {
this.value = cb(this.value);
});
}
})
}
const reject = (cb) => {
setTimeout(() => {
if (this.state === PENDING) {
this.state = REJECTED
this.onRejectedCallbacks.map(cb => {
this.reason = cb(this.reason);
});
}
})
}
try {
fn (resolve, reject)
} catch (error) {
reject (error)
}
}
then (resolve, reject) {
typeof resolve === 'function' && this.onResolveCallBacks.push(resolve)
typeof reject === 'function' && this.onRejectedCallBacks.push(resrejectolve)
return this
}
}
new myPromise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 2000);
})
.then(res => {
console.log(res);
return res + 1;
})
.then(res => {
console.log(res);
});
参考:Promise的源码实现(完美符合Promise/A+规范) - 掘金