Created
January 12, 2021 01:20
-
-
Save trevorhreed/c6e58f312c07cccf144ed495248c549f to your computer and use it in GitHub Desktop.
This file contains 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
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