sindresorhus/eslint-plugin-unicorn

Rule proposal: `prefer-queue-microtask`

Open

#1,346 建立於 2021年6月8日

在 GitHub 查看
 (10 留言) (3 反應) (0 負責人)JavaScript (5,022 star) (468 fork)user submission
help wantednew rule

描述

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

貢獻者指南