-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01.hello.js
More file actions
33 lines (30 loc) · 1.03 KB
/
01.hello.js
File metadata and controls
33 lines (30 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { Worker, isMainThread, parentPort, workerData } from "worker_threads";
import RPCContext from "rpc-magic-proxy";
async function main() {
const ctx = new RPCContext();
const data = {
ping() {
console.log("main: got request ping()");
return "pong";
},
async hello(callback) {
console.log("main: got request hello()");
await callback("world");
},
};
// This will serialize data and send it to worker
const workerData = await ctx.serialize(data);
ctx.bind(new Worker(new URL(import.meta.url), { workerData }));
}
async function worker() {
const ctx = new RPCContext().bind(parentPort);
const data = ctx.deserialize(workerData);
console.log(Object.entries(data));
// Proxy a function call
console.log("client -> ping():", await data.ping()); // pong
// Proxy a function call with callback as argument
await data.hello((msg) => console.log("client -> hello():", msg)); // world
// This will unbind listeners and allow worker to exit
ctx.reset();
}
isMainThread ? main() : worker();