Last active
November 2, 2018 15:16
-
-
Save afterburn/65acf4be9edd85a2c4831264318ea50b to your computer and use it in GitHub Desktop.
Inline web worker
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
const worker = new InlineWorker((data) => { | |
postMessage(data.a + data.b) | |
}) | |
worker.start({ a: 1, b: 2 }, (result) => { | |
console.log(result) // output: 3 | |
}) | |
worker.start({ a: 1, b: 2 }) | |
.then((result) => console.log(result)) | |
.catch((err) => console.error(err)) |
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
class WebWorker { | |
constructor (code) { | |
code = `onmessage = (e) => (${code.toString()})(e.data)` | |
this.blob = window.URL.createObjectURL(new window.Blob([code], { type: 'application/javascript' })) | |
} | |
start (initialData, callback) { | |
if (typeof callback === 'function') { | |
this.worker = new window.Worker(this.blob) | |
this.worker.onmessage = (e) => callback(e.data) | |
this.worker.postMessage(initialData) | |
} else { | |
return new Promise((resolve, reject) => { | |
try { | |
this.worker = new window.Worker(this.blob) | |
this.worker.onmessage = (e) => resolve(e.data) | |
this.worker.postMessage(initialData) | |
} catch (ex) { | |
reject(ex) | |
} | |
}) | |
} | |
} | |
terminate () { | |
this.worker.terminate() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment