class MyPromise {
constructor(fn) {
this.callbacks = [];
this.value = undefined;
this.state = 'pending'
fn(this.resolve.bind(this))
}
resolve(value) {
this.state = 'fulfilled'
this.value = value
this.callbacks.forEach((callback) => { this.hande(callback) })
}
async hande(callback) {
const { onFulfilled, resolve } = callback;
let res=this.value;
if (this.state == 'pending') {
this.callbacks.push(callback)
return
}
if (onFulfilled) {
console.log(111)
res = await onFulfilled(this.value)
console.log(222)
}
console.log(3333)
resolve(res)
// if (!onFulfilled) {
// resolve(this.value)
// return;
// }
// const res = await onFulfilled(this.value)
// resolve(res)
}
then(onFulfilled = null) {
return new MyPromise(resolve => {
this.hande({
onFulfilled,
resolve,
})
})
}
}
let p = new MyPromise((resolve) => {
// resolve(1)
setTimeout(() => { resolve(1) }, 1_000)
}).then((r) => {
console.log(`1:${r}`)
return r
})
.then((r) => new MyPromise((resove, reject) => {
setTimeout(() => {
resove(2)
console.log(`2:${r}`)
}, 1_000 * 4)
})
)
.then((r) => {
console.log(`3:${r}`)
return r
})
.then((r) => {
console.log(`4:${r}`)
return r
})
.then((r) => {
console.log(`5:${r}`)
})
console