简体   繁体   English

javascript中的微任务队列和回调队列

[英]microtask queue and callback queue in javascript

The javascript runtime environment has an event loop, callback queue, and microtask queue. javascript 运行时环境具有事件循环、回调队列和微任务队列。 The functions in the microtask queue get priority over the functions in the callback queue (for getting pushed into the call stack).微任务队列中的函数优先于回调队列中的函数(用于被推入调用堆栈)。

Functions returned from the web API like fetch (which returns a promise) get pushed to the microtask queue while functions returned from web APIs as setTimeout gets pushed to the callback queue.从 web API 返回的函数(如 fetch(返回一个承诺))被推送到微任务队列,而从 web API 作为 setTimeout 返回的函数被推送到队列。 So functions returned by the fetch promise will get executed before the setTimeout.因此 fetch promise 返回的函数将在 setTimeout 之前执行。

My doubt is, the console is also a web API, right??我的疑问是,控制台也是web API吧?? now if we simply want the console to log something then the console web API will return the result which technically should first get stored in the callback queue.现在,如果我们只是想让控制台记录一些东西,那么控制台 web API 将返回从技术上讲应该首先存储在回调队列中的结果。

So here we can observe that a simple console log should get lower priority than a fetch (since the returned function from fetch gets stored in the microtask queue while the console is stored in the callback queue.).所以在这里我们可以观察到一个简单的控制台日志应该比一个 fetch 获得更低的优先级(因为从 fetch 返回的 function 存储在微任务队列中,而控制台存储在回调队列中。)。

So theoretically a function returned from fetch should get executed before a simple console log but in reality, the result is reversed.所以理论上从 fetch 返回的 function 应该在简单的控制台日志之前执行,但实际上,结果是相反的。 So what am I missing?那么我错过了什么? Please someone clear my doubt please.请有人清除我的疑问。

Take a look at this snippet看看这个片段

 setTimeout(() => console.log('ASYNC')) Promise.resolve().then(() => console.log('PROMISE')) // also microtask queueMicrotask(() => console.log('MICROTASK')) console.log('SYNC')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM