.then不符合微任务的执行顺序
来源:8-19 手写 Promise-构造函数

慕瓜1338405
2022-01-21
new MyPromise((resolve,reject) =>{
console.log(1)
resolve(3)
}).then(res =>{
console.log(res)
})
console.log(2)
输出1,3,2 ,和Promise期望不一样。
加个setTimeout处理感觉也不太好
const resolveHandle = (value) =>{
setTimeout(()=>{
this.state = 'fulfilled'
this.value = value
this.resolveCalls.forEach(fn => fn())
})
}
const rejectHandler = (reason) =>{
setTimeout(()=>{
this.state = 'rejected'
this.reason = reason
this.rejectCalls.forEach(fn => fn())
})
}
写回答
1回答
-
双越
2022-01-21
好问题!我自己复现出来了。包括这两行代码,也会有同样的问题
MyPromise.resolve(100).then(res => console.log(res)) console.log(200) // 打印 100 200
目前只能用你说的这种方法来解决。因为 Promise 是一个底层实现的微任务,而我们没法通过其他的 API 去实现 Promise 微任务,只能通过 setTimeout 来模拟一个异步、
012022-02-21
相似问题