diff --git a/examples/worker-threads/node.js b/examples/worker-threads/node.js index 9fac723..977095f 100644 --- a/examples/worker-threads/node.js +++ b/examples/worker-threads/node.js @@ -11,4 +11,12 @@ suite .add('Using import with node: prefix', function () { return import('node:fs'); }) + .add('async test', async function (timer) { + timer.start(); + let i = 0; + while (i++ < timer.count) { + await import("node:fs"); + } + timer.end(timer.count); + }) .run(); diff --git a/lib/worker-runner.js b/lib/worker-runner.js index 7425d60..3b49c10 100644 --- a/lib/worker-runner.js +++ b/lib/worker-runner.js @@ -1,9 +1,17 @@ const { parentPort } = require("node:worker_threads"); const { runBenchmark } = require("./lifecycle"); +const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; // Deserialize the benchmark function function deserializeBenchmark(benchmark) { - benchmark.fn = new Function(benchmark.fn); + const { isAsync, hasArg } = benchmark; + const fnPrototype = isAsync ? AsyncFunction : Function; + + if (hasArg) { + benchmark.fn = new fnPrototype("timer", benchmark.fn); + } else { + benchmark.fn = new fnPrototype(benchmark.fn); + } } parentPort.on( diff --git a/test/worker.js b/test/worker.js index c4de713..95c3396 100644 --- a/test/worker.js +++ b/test/worker.js @@ -21,7 +21,19 @@ describe("Using worker_threads", () => { }) .add("Import without node: prefix", () => { return import("node:fs"); + }) + .add("async test", async () => { + return import("node:fs"); + }) + .add("async with timer", async (timer) => { + timer.start(); + let i = 0; + while (i++ < timer.count) { + await import("node:fs"); + } + timer.end(timer.count); }); + await bench.run(); }); @@ -29,7 +41,7 @@ describe("Using worker_threads", () => { mock.restoreAll(); }); - it("should create a new Worker 2 times", () => { - assert.strictEqual(workerThreads.Worker.mock.calls.length, 2); + it("should create a new Worker 4 times", () => { + assert.strictEqual(workerThreads.Worker.mock.calls.length, 4); }); });