Skip to content

Instantly share code, notes, and snippets.

@roboncode
Created December 30, 2022 17:38
Show Gist options
  • Save roboncode/bc69974c14a69e5eeb0388185a17fde0 to your computer and use it in GitHub Desktop.
Save roboncode/bc69974c14a69e5eeb0388185a17fde0 to your computer and use it in GitHub Desktop.
Dynamic web worker
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)
})
})
}
}
@roboncode
Copy link
Author

const getTodo = createWorker(async id => {
    return fetch('https://jsonplaceholder.typicode.com/todos/' + id).then(response => response.json())
      .then(json => console.log(json))
 })
 
const result = await getTodo(2)
console.log('todo:', result)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment