queueMicrotask(callback)
稳定性: 2 - 稳定的
¥Stability: 2 - Stable
-
callback
<Function> 要排队的函数。¥
callback
<Function> Function to be queued.
queueMicrotask()
方法将微任务排队以调用 callback
。如果 callback
抛出异常,将触发 process
对象 'uncaughtException'
事件。
¥The queueMicrotask()
method queues a microtask to invoke callback
. If
callback
throws an exception, the process
object 'uncaughtException'
event will be emitted.
微任务队列由 V8 管理,并且可以以类似于 process.nextTick()
队列的方式使用,后者由 Node.js 管理。在 Node.js 事件循环的每次轮询中,process.nextTick()
队列总是在微任务队列之前处理。
¥The microtask queue is managed by V8 and may be used in a similar manner to
the process.nextTick()
queue, which is managed by Node.js. The
process.nextTick()
queue is always processed before the microtask queue
within each turn of the Node.js event loop.
// Here, `queueMicrotask()` is used to ensure the 'load' event is always
// emitted asynchronously, and therefore consistently. Using
// `process.nextTick()` here would result in the 'load' event always emitting
// before any other promise jobs.
DataHandler.prototype.load = async function load(key) {
const hit = this._cache.get(key);
if (hit !== undefined) {
queueMicrotask(() => {
this.emit('load', hit);
});
return;
}
const data = await fetchData(key);
this._cache.set(key, data);
this.emit('load', data);
};