diff options
author | Gus Caplan <me@gus.host> | 2018-09-19 18:33:52 +0300 |
---|---|---|
committer | Gus Caplan <me@gus.host> | 2018-09-23 23:57:19 +0300 |
commit | de0441f6f677b338b78752b8fbaac767fdf35075 (patch) | |
tree | 6257215ec115f9c47457bdd109e7ad9b71af7cb3 /doc/api/globals.md | |
parent | 59a8324d2793c504fc81a3126478d8c401df314e (diff) |
lib: implement queueMicrotask
PR-URL: https://github.com/nodejs/node/pull/22951
Refs: https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-queuemicrotask
Reviewed-By: Bradley Farias <bradley.meck@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Diffstat (limited to 'doc/api/globals.md')
-rw-r--r-- | doc/api/globals.md | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/doc/api/globals.md b/doc/api/globals.md index af0bf3ee674..a461dca2ae2 100644 --- a/doc/api/globals.md +++ b/doc/api/globals.md @@ -107,6 +107,46 @@ added: v0.1.7 The process object. See the [`process` object][] section. +## queueMicrotask(callback) +<!-- YAML +added: REPLACEME +--> + +<!-- type=global --> + +> Stability: 1 - Experimental + +* `callback` {Function} Function to be queued. + +The `queueMicrotask()` method queues a microtask to invoke `callback`. If +`callback` throws an exception, the [`process` object][] `'error'` event will +be emitted. + +In general, `queueMicrotask` is the idiomatic choice over `process.nextTick()`. +`process.nextTick()` will always run before microtasks, and so unexpected +execution order may be observed. + +```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(url); + if (hit !== undefined) { + queueMicrotask(() => { + this.emit('load', hit); + }); + return; + } + + const data = await fetchData(key); + this._cache.set(url, data); + this.emit('load', data); +}; +``` + ## require() This variable may appear to be global but is not. See [`require()`]. |