Created
November 9, 2020 18:44
-
-
Save ChaosEngine/ef185cd13b11b88630a33d895fb76c4e to your computer and use it in GitHub Desktop.
WebWorkerify of any JS funcion
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
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); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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);