Last active
August 25, 2021 01:39
-
-
Save socheatsok78/7ede85c6f479bb8c0b35c7114a6c3edf to your computer and use it in GitHub Desktop.
Example of `are-you-ready-yet` used with `Comlink`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { bridge } from './test-bridge.js' | |
bridge.doThis() | |
setTimeout(async () => { | |
bridge.create() | |
setTimeout(async () => { | |
await bridge.doThat() | |
}, 5000); | |
}, 5000); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { areYouReadyYet } from 'are-you-ready-yet' | |
import * as Comlink from 'comlink' | |
import TestWorker from 'worker-loader!./test-worker' | |
class TestBridge { | |
constructor(options = null) { | |
this.ready = areYouReadyYet() | |
/** @type {Worker} */ | |
const worker = new TestWorker() | |
/** @type {Comlink.Remote<import('./test-worker').Test} */ | |
const remote = Comlink.wrap(worker) | |
this.worker = worker | |
this.remote = remote | |
/** @type {import('./test-worker').Test} */ | |
this.instance = null | |
// If options provided, immediate create instance | |
if (options) this.create(options) | |
} | |
async create(options = {}) { | |
// If already created, ignore | |
if (this.instance) return this.instance | |
const Instance = this.remote | |
const remote = new Instance(options) | |
this.instance = await remote | |
// Send ready signal | |
this.ready.yes() | |
return this.instance | |
} | |
async doThis() { | |
await this.ready.maybe() | |
this.instance.doThis() | |
} | |
async doThat() { | |
await this.ready.maybe() | |
this.instance.doThat() | |
} | |
terminate() { | |
this.remote[Comlink.releaseProxy]() | |
this.worker.terminate() | |
// Re-create ready promise | |
this.ready = areYouReadyYet() | |
} | |
} | |
export const bridge = new TestBridge() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as Comlink from 'comlink' | |
export class Test { | |
constructor(options = {}) { | |
console.info('Test.constructor', options) | |
} | |
doThis() { | |
console.info('Test.doThis') | |
} | |
doThat() { | |
console.info('Test.doThat') | |
} | |
} | |
Comlink.expose(Test) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment