Skip to content

Instantly share code, notes, and snippets.

@ChaosEngine
Created November 9, 2020 18:44
Show Gist options
  • Save ChaosEngine/ef185cd13b11b88630a33d895fb76c4e to your computer and use it in GitHub Desktop.
Save ChaosEngine/ef185cd13b11b88630a33d895fb76c4e to your computer and use it in GitHub Desktop.
WebWorkerify of any JS funcion
Function.prototype.callAsWorker = function (context, args) {
return new Promise((resolve, reject) => {
const code = `
${context ? [...context].reduce((acc, cur) => acc + cur.toString() + '\n') : ''}
self.onmessage = async function (e) {
const result = await ( ${this.toString()}.call(null, e.data) );
self.postMessage( result );
}`,
blob = new Blob([code], { type: "text/javascript" }),
worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = e => (resolve(e.data), worker.terminate(), window.URL.revokeObjectURL(blob));
worker.onerror = e => (reject(e.message), worker.terminate(), window.URL.revokeObjectURL(blob));
worker.postMessage(args);
});
};
@ChaosEngine
Copy link
Author

this is beautiful stuff. Run async web-worker code from any function...well almost

@ChaosEngine
Copy link
Author

Usage:
function LocalLog(msg) {
// eslint-disable-next-line no-console
console.log(msg);
}
function someFunc(params){
const res = params.one + params.two;
LocalLog('worker res = ' + res);
}
const result = await someFunc.callAsWorker(
//context function passed in to worker
[LocalLog],
//parameters
{
one: 123, two: 467
}
);
LocalLog('Result returned from worker res = ' + res);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment