當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js queueMicrotask(callback)用法及代碼示例

queueMicrotask(callback)

添加於:v11.0.0

參數

queueMicrotask()方法將要調用的微任務排隊callback.如果callback拋出異常,process 對象 'uncaughtException'將發出事件。

微任務隊列由 V8 管理,使用方式與 process.nextTick() 隊列類似,後者由 Node.js 管理。 process.nextTick() 隊列總是在 Node.js 事件循環的每一輪中的微任務隊列之前處理。

// 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);
};

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 queueMicrotask(callback)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。