大量通过 proxy 来实现的.
<!DOCTYPE html>
<script type="module">
// import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";
// import * as Comlink from "../../../dist/esm/comlink.mjs";
import * as Comlink from "./comlink.mjs";
async function init() {
const worker = new Worker("worker.js");
// WebWorkers use `postMessage` and therefore work with Comlink.
const obj = Comlink.wrap(worker);
console.log(`Counter: ${await obj.counter}`);
let incRet = await obj.inc();
console.log(`Counter: ${await obj.counter}`);
console.log(`return a`, await incRet.a)
console.log(`return b`, await incRet.b)
console.log("calling b");
console.log(`b called :`, await incRet.b());
// console.log(`Incremented return:`, incRet, JSON.stringify(incRet));
// console.log(`properties:`, incRet.a, incRet.b);
}
init();
</script>
worker.js
// importScripts("https://unpkg.com/comlink/dist/umd/comlink.js");
// importScripts("../../../dist/umd/comlink.js");
importScripts("./comlink.js");
const obj = {
counter: 0,
inc() {
this.counter++;
return Comlink.proxy({
a: 1,
b: Comlink.proxy(() => {
console.log("b called inside");
})
})
},
};
Comlink.expose(obj);
输出
// [main] request response message {type: 'GET', path: Array(1)}
// [worker] Sending response {type: 'RAW', value: 0}
(index):29 Counter: 0
// [main] request response message {type: 'APPLY', path: Array(1), argumentList: Array(0)}
// [worker] Sending response {type: 'HANDLER', name: 'proxy', value: MessagePort}
// [main] request response message {type: 'GET', path: Array(1)}
// [worker] Sending response {type: 'RAW', value: 1}
(index):32 Counter: 1
// [main] request response message {type: 'GET', path: Array(1)}
// [worker] Sending response {type: 'RAW', value: 1}
(index):34 return a 1
// [main] request response message {type: 'GET', path: Array(1)}
// [worker] Sending response {type: 'HANDLER', name: 'proxy', value: MessagePort}name: "proxy"type: "HANDLER"value: MessagePort {onmessage: null, onmessageerror: null}[[Prototype]]: Object
(index):35 return b Proxy(Function) {length: 0, name: 'target', prototype: {…}}
(index):37 calling b
// [main] request response message {type: 'APPLY', path: Array(1), argumentList: Array(0)}
worker.js:50 b called inside
// [worker] Sending response {type: 'RAW', value: undefined}
(index):38 b called : undefined
// [main] request response message {type: 'RELEASE'}
// [main] request response message {type: 'RELEASE'}
// [worker] Sending response {type: 'RAW', value: undefined}
// [worker] Sending response {type: 'RAW', value: undefined}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。