From 8ab20a4582016542ac3d8140593f817ab920005f Mon Sep 17 00:00:00 2001 From: Steven Guerrero Date: Mon, 16 Nov 2020 14:44:37 -0500 Subject: [PATCH] feat(std/node): implement process.nextTick (#8386) --- std/node/process.ts | 20 ++++++++++++++++++++ std/node/process_test.ts | 21 +++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/std/node/process.ts b/std/node/process.ts index a47140f150..6f61a074a0 100644 --- a/std/node/process.ts +++ b/std/node/process.ts @@ -28,6 +28,25 @@ export const versions = { ...Deno.version, }; +/** https://nodejs.org/api/process.html#process_process_nexttick_callback_args */ +export function nextTick(this: unknown, cb: () => void): void; +export function nextTick>( + this: unknown, + cb: (...args: T) => void, + ...args: T +): void; +export function nextTick>( + this: unknown, + cb: (...args: T) => void, + ...args: T +) { + if (args) { + queueMicrotask(() => cb.call(this, ...args)); + } else { + queueMicrotask(cb); + } +} + /** https://nodejs.org/api/process.html#process_process */ // @deprecated `import { process } from 'process'` for backwards compatibility with old deno versions export const process = { @@ -123,6 +142,7 @@ export const process = { // Getter also allows the export Proxy instance to function as intended return Deno.env.toObject(); }, + nextTick, }; /** diff --git a/std/node/process_test.ts b/std/node/process_test.ts index 6e6145e677..ee566853e3 100644 --- a/std/node/process_test.ts +++ b/std/node/process_test.ts @@ -5,6 +5,7 @@ import { assert, assertEquals, assertThrows } from "../testing/asserts.ts"; import * as path from "../path/mod.ts"; import * as all from "./process.ts"; import { argv, env } from "./process.ts"; +import { delay } from "../async/delay.ts"; // NOTE: Deno.execPath() (and thus process.argv) currently requires --allow-env // (Also Deno.env.toObject() (and process.env) requires --allow-env but it's more obvious) @@ -164,3 +165,23 @@ Deno.test({ // assert(process.stderr.isTTY); }, }); + +Deno.test({ + name: "process.nextTick", + async fn() { + let withoutArguments = false; + process.nextTick(() => { + withoutArguments = true; + }); + + const expected = 12; + let result; + process.nextTick((x: number) => { + result = x; + }, 12); + + await delay(10); + assert(withoutArguments); + assertEquals(result, expected); + }, +});