Created
December 30, 2022 17:38
-
-
Save roboncode/bc69974c14a69e5eeb0388185a17fde0 to your computer and use it in GitHub Desktop.
Dynamic web worker
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 createWorker(fn) { | |
// Create a Blob object that contains the code for the worker | |
// create wrapper function that calls the function passed to createWorker | |
// and then posts the result back to the main thread | |
const fnStr = fn.toString() | |
// wrap the function in a function that calls the function and posts the result | |
const wrapper = `async function(evt) { | |
const fn = ${fnStr} | |
try { | |
const result = await fn(...evt.data) | |
postMessage(result) | |
} catch (e) { | |
postMessage(e) | |
} | |
}` | |
var blob = new Blob(['self.onmessage = ', wrapper], { | |
type: 'text/javascript', | |
}) | |
// Create an object URL for the blob | |
var url = window.URL.createObjectURL(blob) | |
// Create a new Worker using the object URL | |
var worker = new Worker(url) | |
// Return an async function that can be used to run the worker's function and receive the result | |
return async function (...args) { | |
// Send a message to the worker with the arguments for the function | |
worker.postMessage(JSON.parse(JSON.stringify(args))) | |
// Wait for the response from the worker | |
return new Promise((resolve, reject) => { | |
worker.addEventListener('message', event => { | |
// Resolve the promise with the result from the worker | |
resolve(event.data) | |
}) | |
}) | |
} | |
} |
Author
roboncode
commented
Dec 30, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment