Skip to content

Instantly share code, notes, and snippets.

@trevorhreed
Created January 12, 2021 01:20
Show Gist options
  • Save trevorhreed/c6e58f312c07cccf144ed495248c549f to your computer and use it in GitHub Desktop.
Save trevorhreed/c6e58f312c07cccf144ed495248c549f to your computer and use it in GitHub Desktop.
export class UnitWorkerManager {
private resolves = {}
private rejects = {}
private promiseId = 0
private worker
constructor(scriptPath, opts) {
this.worker = new Worker(scriptPath, opts)
this.worker.addEventListener('message', data => {
const { id, err, result } = data || {}
if (!id) throw `Received message from web worker without id!`
const resolve = this.resolves[id]
const reject = this.rejects[id]
if (err && reject) {
reject(err)
} else if (result && resolve) {
resolve(result)
}
})
this.worker.addEventListener('error', err => {
throw err
})
}
async request<T>(args): Promise<T> {
const id = ++this.promiseId
const result = await new Promise((resolve, reject) => {
this.resolves[id] = resolve
this.rejects[id] = reject
this.worker.postMessage({ id, args })
})
return result as T
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment