Microtask
一句话解释
microtask 是 短 函数 那个 运行 之后 current 任务 completes 但 之前 下一个 macrotask — primarily Promise 回调.
用大白话说
Microtasks 是小 函数 queued 通过 Promise resolutions (and queueMicrotask()) that run after the current synchronous code finishes but before any macrotask (like setTimeout). The event loop drains the entire microtask queue before moving to the next macrotask.
This means all pending Promise callbacks run before the next setTimeout callback, even if the setTimeout was registered first. This is why Promise.resolve().然后(() => ...) runs before setTimeout(() => ..., 0).
Understanding microtasks vs macrotasks is important for predicting the order of async code execution and avoiding subtle bugs in complex async flows.
示例
setTimeout(() => console.log("macrotask"), 0);
Promise.resolve().then(() => console.log("microtask"));
console.log("sync");
// Output: sync, microtask, macrotaskMicrotasks (Promise) 运行 之前 macrotasks (setTimeout).
相关术语
相关资源
相关课程
- 异步 JavaScript
学习 关于 microtasks.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。