class _Promise {
constructor(callback) {
this.state = "PENDING"
this.result = "null"
this.tasks = []
const resolve = (result) => {
if (result instanceof _Promise) {
result.then(resolve)
return;
}
this.state = "FULFILLED"
this.result = result
this.tasks.forEach(cb => {
this.handler(cb)
})
}
callback(resolve)
}
handler(cb) {
if (this.state === "PENDING") {
this.tasks.push(cb)
return;
}
if (!cb.onFulfilled) {
cb.resolve()
}
const ret = cb.onFulfilled(this.result)
cb.resolve(ret)
}
then(onFulfilled) {
return new _Promise((resolve) => {
this.handler({
onFulfilled,
resolve
})
})
}
}
new _Promise(resolve => {
console.log(1)
setTimeout(resolve, 10, 2)
})
.then(res => {
console.log(res)
return new _Promise(resolve => {
console.log(3)
setTimeout(resolve, 10, 4)
})
})
.then(res => console.log(res))