我一直在玩Promises,但是在理解以下代码发生的事情时遇到了麻烦:
const promise = new Promise((resolve, reject) => {
console.log('Promise started')
resolve('Success')
})
setTimeout(() => {
console.log('Log inside first setTimeout')
}, 0)
promise.then(res => {
console.log('Promise log after fulfilled ❌')
})
setTimeout(() => {
console.log('Log inside second setTimeout')
}, 0)
输出为:
Promise started
Promise log after fulfilled ❌
Log inside first setTimeout
Log inside second setTimeout
为什么不是下面的输出?
Promise started
Log inside first setTimeout
Log inside second setTimeout
Promise log after fulfilled ❌
在setTimeout(fn, 0)
fn呼叫和resolve()
fn呼叫之间,将被赋予优先级?
是否取决于浏览器的实现细节?
setTimeout
是宏任务-在包括Promises在内的微任务之后解决。 setTimeout
是非阻塞的,因此代码先执行(包括.then
),然后执行第一个setTimeout
,然后执行第二个setTimeout
。
承诺具有更高的优先级,因为它们在微任务队列中排队。首先处理微任务队列中的任务。然后处理其他计划任务,在这种情况下为setTimeout
。