Skip to content

Instantly share code, notes, and snippets.

@keeferrourke
Created June 9, 2020 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keeferrourke/839e5541130d28cccca70cc259f538d3 to your computer and use it in GitHub Desktop.
Save keeferrourke/839e5541130d28cccca70cc259f538d3 to your computer and use it in GitHub Desktop.
A little JS class to help with running functions in web workers.
/**
* 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