sindresorhus/eslint-plugin-unicorn

Rule proposal: `prefer-queue-microtask`

Geschlossen

#1.346 geöffnet am 08.06.2021

 (10 Kommentare) (3 Reaktionen) (0 zugewiesene Personen)JavaScript (468 Forks)user submission
help wantednew rule

Repository-Metriken

Stars
 (5.022 Sterne)
PR-Merge-Metriken
 (Durchschn. Merge 1T 16h) (399 gemergte PRs in 30 T)

Beschreibung

queueMicrotask() serves a similar purpose to process.nextTick() with the additional advantage that queueMicrotask() is specified in the WHATWG HTML Living Standard and supported on both modern browsers and Node.js (v11.0.0 and later).

When to use queueMicrotask() vs. process.nextTick() in the Node.js API documentation states:

For most userland use cases, the queueMicrotask() API provides a portable and reliable mechanism for deferring execution that works across multiple JavaScript platform environments and should be favored over process.nextTick(). In simple scenarios, queueMicrotask() can be a drop-in replacement for process.nextTick().

I propose adding a rule to warn when process.nextTick is used, and suggest queueMicrotask() as an alternative.

Fail

process.nextTick(() => process.exit(0));
process.nextTick(process.exit);
process.nextTick(process.exit, 1);
const fun = process.nextTick;
fun(process.nextTick);

Pass

queueMicrotask(() => process.exit(0));
queueMicrotask(process.exit);
// Note: queueMicrotask takes exactly 1 arg.
// Fail example fixed using .bind().
queueMicrotask(process.exit.bind(undefined, 1));
// Not sure if this should be auto-fixed.
// fun may be called with multiple args.
const fun = queueMicrotask;
// Not sure if this should be auto-fixed.
// fun may call its argument with multiple args.
fun(process.nextTick);

Contributor Guide