[英]Event loop, Promise and setTimeout
Consider the following code.考虑以下代码。 I don't quite understand why it works this way.
我不太明白为什么它会这样工作。
setTimeout
, so it registers it in web APIs (or somewhere else)setTimeout
,所以它会在 Web API(或其他地方)中注册它 I know that microtask queue has higher priority and should be executed before callbacks from macrotask queue, however it is not the case.我知道微任务队列具有更高的优先级,应该在宏任务队列的回调之前执行,但事实并非如此。 Please explain why.
请解释原因。
setTimeout(() => { console.log("Timer"); }, 1000); let p = new Promise(res => { setTimeout(() => { res("Promise"); }, 1500); }); p.then(msg => console.log(msg)); let start = new Date().getTime(); let stop = start; while (stop !== start + 2000){ stop = new Date().getTime(); }
Your second setTimeout
indeed does begin when you expected it to, but until JS goes looking for whether it has finished, it can't officially finish.你的第二个
setTimeout
确实在你预期的时候开始了,但是直到 JS 去寻找它是否已经完成,它才能正式完成。 That process of looking for whether a setTimeout has finished, is officially a macrotask
.寻找 setTimeout 是否已完成的过程,正式是一个
macrotask
。 The promise resolution (after that) is a microtask.承诺决议(在那之后)是一个微任务。
So for that promise to resolve requires two things to happen: setTimeout timer to be reviewed by JS, and the promise to resolve.因此,要解决该承诺需要发生两件事:由 JS 审查的 setTimeout 计时器,以及要解决的承诺。 The former is the bottleneck in your case.
前者是您的情况的瓶颈。
setTimeout(() => { console.log("Timer"); }, 1000); let p = new Promise(res => { setTimeout(() => { res("Promise"); }, 1500); console.log("setTimeout #2 has begun ticking") }); p.then(msg => console.log(msg)); let start = new Date().getTime(); let stop = start; while (stop !== start + 2000){ stop = new Date().getTime(); }
setTimeout(() => { console.log("Timer"); }, 1000); let p = new Promise(res => { setTimeout(() => { res("Promise"); }, 500); console.log("setTimeout #2 has begun ticking") }); p.then(msg => console.log(msg)); let start = new Date().getTime(); let stop = start; while (stop !== start + 2000){ stop = new Date().getTime(); }
The second program has the "Promise" printed before "Timer!".第二个程序在“Timer!”之前打印了“Promise”。
setTimeout()
with "Timer" is scheduled for 1 second later.setTimeout()
安排在 1 秒后。 Let's call this timer1 .setTimeout()
that will resolve the promise in 1.5 seconds.setTimeout()
将在 1.5 秒内解决承诺。 Let's call this timer2 ..then()
adds a callback to run after the promise is resolved. .then()
添加了一个回调以在承诺解决后运行。 Let's call this promiseCallback ."Timer"
."Timer"
。"Promise"
."Promise"
解析承诺。"Promise"
."Promise"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.