worker-fn
隐藏了 JavaScript 主线程与
Worker
线程之间的通信的复杂性,可以让你方便地调用定义在 Worker 中的函数。
你可以通过 worker-fn
在 JavaScript
主线程中创建函数签名与工作函数一致的代理函数(除了代理函数的返回值会被包裹在
Promise 中),代理函数会通过消息事件调用定义在 Worker 中的对应的工作函数。
math.worker.js
:
import { defineWorkerFn } from "worker-fn";
function add(a, b) {
return a + b;
}
function fib(n) {
return n <= 2 ? 1 : fib(n - 1) + fib(n - 2);
}
defineWorkerFn("add", add);
defineWorkerFn("fib", fib);
math.js
:
import { useWorkerFn } from "worker-fn";
const worker = new Worker(new URL("./math.worker.js", import.meta.url), {
type: "module",
});
const add = useWorkerFn("add", worker);
const fib = useWorkerFn("fib", worker);
console.log(await add(1, 2)); // 3
console.log(await fib(5)); // 5
例子
math.worker.js
:
import { defineWorkerFns } from "worker-fn";
const fns = {
add(a, b) {
return a + b;
},
fib(n) {
return n <= 2 ? 1 : fns.fib(n - 1) + fns.fib(n - 2);
},
};
defineWorkerFns(fns);
math.js
:
import { useWorkerFns } from "worker-fn";
const worker = new Worker(new URL("./math.worker.js", import.meta.url), {
type: "module",
});
const { add, fib } = useWorkerFns(worker);
console.log(await add(1, 2)); // 3
console.log(await fib(5)); // 5
例子
math.worker.ts
:
import { defineWorkerFn } from "worker-fn";
function add(a: number, b: number) {
return a + b;
}
function fib(n: number): number {
return n <= 2 ? 1 : fib(n - 1) + fib(n - 2);
}
defineWorkerFn("add", add);
defineWorkerFn("fib", fib);
export type Add = typeof add;
export type Fib = typeof fib;
math.ts
:
import { useWorkerFn } from "worker-fn";
import type { Add, Fib } from "./math.worker.ts";
const worker = new Worker(new URL("./math.worker.ts", import.meta.url), {
type: "module",
});
const add = useWorkerFn<Add>("add", worker);
const fib = useWorkerFn<Fib>("fib", worker);
console.log(await add(1, 2)); // 3
console.log(await fib(5)); // 5
例子
math.worker.js
:
import { parentPort } from "node:worker_threads";
import { defineWorkerFn } from "worker-fn";
function add(a, b) {
return a + b;
}
function fib(n) {
return n <= 2 ? 1 : fib(n - 1) + fib(n - 2);
}
defineWorkerFn("add", add, { port: parentPort });
defineWorkerFn("fib", fib, { port: parentPort });
math.js
:
import { Worker } from "node:worker_threads";
import { useWorkerFn } from "worker-fn";
const worker = new Worker(new URL("./math.worker.js", import.meta.url));
const add = useWorkerFn("add", worker);
const fib = useWorkerFn("fib", worker);
console.log(await add(1, 2)); // 3
console.log(await fib(5)); // 5