MCPcopy Create free account
hub / github.com/MultithreadedJSBook/code-samples / RpcWorker

Class RpcWorker

ch2-patterns/rpc-worker.js:1–28  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class RpcWorker {
2 constructor(path) {
3 this.next_command_id = 0;
4 this.in_flight_commands = new Map();
5 this.worker = new Worker(path);
6 this.worker.onmessage = this.onMessageHandler.bind(this);
7 }
8// THIS LINE SHOULD NOT APPEAR IN PRINT
9 onMessageHandler(msg) {
10 const { result, error, id } = msg.data;
11 const { resolve, reject } = this.in_flight_commands.get(id);
12 this.in_flight_commands.delete(id);
13 if (error) reject(error);
14 else resolve(result);
15 }
16// THIS LINE SHOULD NOT APPEAR IN PRINT
17 exec(method, ...args) {
18 const id = ++this.next_command_id;
19 let resolve, reject;
20 const promise = new Promise((res, rej) => {
21 resolve = res;
22 reject = rej;
23 });
24 this.in_flight_commands.set(id, { resolve, reject });
25 this.worker.postMessage({ method, params: args, id });
26 return promise;
27 }
28}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected