Last active
April 27, 2022 19:07
-
-
Save literallylara/d360e2c0b048f2a56a7bd25f3563da7f 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
/** | |
* Promise wrapper for web workers. | |
* | |
* @author Lara Sophie Schütt (@literallylara) | |
* @license MIT | |
*/ | |
export default class PromiseWorker | |
{ | |
constructor(fn, ...args) | |
{ | |
return new Promise((resolve, reject) => | |
{ | |
if (typeof fn != "function") | |
{ | |
reject("Expected function at first argument") | |
return | |
} | |
const script = `onmessage = e => postMessage((${fn})(...e.data))` | |
const url = "data:application/javascript;base64," + btoa(script) | |
const worker = new Worker(url) | |
worker.onmessage = e => | |
{ | |
resolve(e.data) | |
worker.terminate() | |
} | |
worker.onmessageerror = worker.onerror = e => | |
{ | |
reject(e) | |
worker.terminate() | |
} | |
worker.postMessage(args) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: