Skip to content

Instantly share code, notes, and snippets.

@dtipson
Last active June 5, 2017 09:41
Show Gist options
  • Save dtipson/e5dcfda63f97ca83fb4ff7364927a329 to your computer and use it in GitHub Desktop.
Save dtipson/e5dcfda63f97ca83fb4ff7364927a329 to your computer and use it in GitHub Desktop.
Another simple implementation of pushing a potentially costly operation off to a worker thread
//main function for creating an inline worker:
//inlineWorker:: Function -> a -> Promise b
const inlineWorker = fn => msg => {
const scriptString = `const func = ${fn.toString()};
addEventListener('message', function(e) {
Promise.resolve(e.data)
.then(func)
.then(postMessage);
}, false);
`;
//promisify the response/error for make things easier to consume
const promise = new Promise( (resolve, reject) => {
const blob = new Blob([scriptString], { type: "text/javascript" });
const bloblurl = window.URL.createObjectURL(blob);
const worker = new Worker(bloblurl);
worker.onmessage = e => {
resolve(e.data);
window.URL.revokeObjectURL(bloblurl);//remember to free up the blob url as well
worker.terminate();
};
worker.onerror = e => {
reject(e);
window.URL.revokeObjectURL(bloblurl);
worker.terminate();
};
worker.postMessage(msg);
});
return promise;
}
//examples
//one line usage
inlineWorker(x=>x+1)(6).then(x=>console.log('msg returned: ',x));//logs "7"
//or elevate functions for repeated usage
const addOneWW = inlineWorker(x=>x+1);
//returns a promise-returning function that will take
//a value and run the function on it... just in a webworker
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment