Created
June 9, 2020 15:21
-
-
Save keeferrourke/839e5541130d28cccca70cc259f538d3 to your computer and use it in GitHub Desktop.
A little JS class to help with running functions in web workers.
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
/** | |
* WorkerScope prepares a function to be run in a web worker | |
* without needing an external JavaScript file or forcing you | |
* to deal with event listener. | |
* | |
* Example usage: | |
* | |
* await result = new WorkerScope( | |
* () => self.postMessage('hi!') | |
* ).run() // 'hi' | |
*/ | |
class WorkerScope { | |
/** | |
* @param {Function} fun The function to run in a worker. | |
* @param {Object} args The args to start the worker with. | |
*/ | |
constructor(fun, args = 0) { | |
this.fun = fun; | |
this.args = args; | |
} | |
/** | |
* Returns a pending promise with the result of the worker task. | |
*/ | |
run() { | |
return new Promise(resolve => { | |
// Construct the web worker. | |
const blob = new Blob( | |
[`onmessage=${this.fun}`], | |
{ type: 'application/javascript' } | |
); | |
const blobURL = URL.createObjectURL(blob); | |
const worker = new Worker(blobURL); | |
URL.revokeObjectURL(blobURL); | |
worker.onmessage = function (e) { | |
return resolve(e.data); | |
}; | |
// Start the worker. | |
worker.postMessage(this.args) | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment