Hi 🙋‍♀️about me 😎posts 📚

Node.js v11.0.0 から queueMicrotask というメソッドが Global Objects に生えてました

:memo: queueMicrotask

Stability: 1 - Experimental

たまたま doc を見ていたらたまたま見つけたのでたまたま調べてみました。

その名の通り、microtask に 関数を enqueue できるようになる メソッドらしいです。

Node.js は v.11.0.0 から試せます。

$ node -v; node --no-warnings
v11.0.0
> queueMicrotask
[Function: queueMicrotask]
>

一応 chrome にも実装されているっぽい https://www.chromestatus.com/feature/5111086432911360

この issue が proposal っぽい?

要すると、今まで microTask で cb を実行させるには Promise なり MutationObserver|process.nextTick でラップする必要があって分かりにくいやーんって感じなのかな

さっと確認用の script を書いたので event loop に自信ニキは結果を予想してみてください

console.log("start:main");

const syncFn = v => () => {
  console.log(v);
};

setImmediate(syncFn("imidiate"));
setTimeout(syncFn("setTimeout"));

queueMicrotask(syncFn("qmt"));
Promise.resolve().then(syncFn("resolve"));
process.nextTick(syncFn("nt"));

queueMicrotask(() => queueMicrotask(syncFn("qmt:r")));
Promise.resolve().then(() => Promise.resolve().then(syncFn("resolve:r")));
process.nextTick(() => process.nextTick(syncFn("nt:r")));

Promise.resolve().then(syncFn("resolve2"));
queueMicrotask(syncFn("qmt2"));
process.nextTick(syncFn("nt2"));

console.log("end:main");

結果はこんな感じです

$  node --no-warnings sample.js
start:main
end:main
nt
nt2
nt:r
qmt
resolve
resolve2
qmt2
qmt:r
resolve:r
setTimeout
imidiate

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.

とあるので、Promise.resolve().then(cb) としてたとこの代替っぽく使えそう。

明示的な API でワイ的には結構すこなので Stable までいってほしいところ。

fin.