Skip to content

Instantly share code, notes, and snippets.

@socheatsok78
Last active August 25, 2021 01:39
Show Gist options
  • Save socheatsok78/7ede85c6f479bb8c0b35c7114a6c3edf to your computer and use it in GitHub Desktop.
Save socheatsok78/7ede85c6f479bb8c0b35c7114a6c3edf to your computer and use it in GitHub Desktop.
Example of `are-you-ready-yet` used with `Comlink`
import { bridge } from './test-bridge.js'
bridge.doThis()
setTimeout(async () => {
bridge.create()
setTimeout(async () => {
await bridge.doThat()
}, 5000);
}, 5000);
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()
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