Last active
June 5, 2017 09:41
-
-
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
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
//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