const PENDING = 'pending';
const REJECTED = 'rejected';
const FULFILLED = 'fulfilled';
class myPromise {
constructor(executor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = []
this.onRejectedCallbacks = []
const resolve = value => {
if (this.status == PENDING) {
this.status = FULFILLED
this.value = value;
this.onFulfilledCallbacks.forEach(callback => callback(value))
}
}
const reject = reason => {
if (this.status == PENDING) {
this.status = REJECTED;
this.reason = reason;
this.onRejectedCallbacks.forEach(callback => callback(reason))
}
}
try {
executor(resolve, reject)
} catch (err) {
reject(err)
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }
if (this.status === FULFILLED) onFulfilled(this.value)
if (this.status === REJECTED) onRejected(this.reason)
if (this.status === PENDING) {
this.onFulfilledCallbacks.push(onFulfilled.bind(this))
this.onRejectedCallbacks.push(onRejected.bind(this))
}
}
}
const p = new myPromise((resove, reject) => {
resove('success')
reject('err')
})
p.then(reason => console.log(reason))
const p1 = new myPromise((resolve, reject) => {
setTimeout(() => {
const rand = Math.random() * 100
if (rand >= 50) {
resolve('success')
} else {
reject('error')
}
}, 1000)
})
p1.then(res=>console.log(res))
console