Last active
June 27, 2023 05:38
-
-
Save sergiodxa/06fabb866653bd8b3165e9fe9fd8036b to your computer and use it in GitHub Desktop.
Use WebWorkers and promises to run sync heavy functions in a worker (process) and get the result in a promise
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
function asyncThread(fn, ...args) { | |
if (!window.Worker) throw Promise.reject( | |
new ReferenceError(`WebWorkers aren't available.`) | |
); | |
const fnWorker = ` | |
self.onmessage = function(message) { | |
(${fn.toString()}) | |
.apply(null, message.data) | |
.then(result => self.postMessage(result)); | |
}`; | |
return new Promise((resolve, reject) => { | |
try { | |
const blob = new Blob([fnWorker], { type: 'text/javascript' }); | |
const blobUrl = window.URL.createObjectURL(blob); | |
const worker = new Worker(blobUrl); | |
window.URL.revokeObjectURL(blobUrl); | |
worker.onmessage = result => { | |
resolve(result.data); | |
worker.terminate(); | |
}; | |
worker.onerror = error => { | |
reject(error); | |
worker.terminate(); | |
}; | |
worker.postMessage(args); | |
} catch (error) { | |
reject(error); | |
} | |
}); | |
} |
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
function thread(fn, ...args) { | |
if (!window.Worker) throw Promise.reject( | |
new ReferenceError(`WebWorkers aren't available.`) | |
); | |
const fnWorker = ` | |
self.onmessage = function(message) { | |
self.postMessage( | |
(${fn.toString()}).apply(null, message.data) | |
); | |
}`; | |
return new Promise((resolve, reject) => { | |
try { | |
const blob = new Blob([fnWorker], { type: 'text/javascript' }); | |
const blobUrl = window.URL.createObjectURL(blob); | |
const worker = new Worker(blobUrl); | |
window.URL.revokeObjectURL(blobUrl); | |
worker.onmessage = result => { | |
resolve(result.data); | |
worker.terminate(); | |
}; | |
worker.onerror = error => { | |
reject(error); | |
worker.terminate(); | |
}; | |
worker.postMessage(args); | |
} catch (error) { | |
reject(error); | |
} | |
}); | |
} | |
// example with an async/await function | |
(async () => { | |
try { | |
const res1 = await thread( | |
str => JSON.parse(str), | |
'{"key": "value"}' | |
); | |
console.log(res1); | |
} catch (error) { | |
console.error(error); | |
} | |
})(); | |
// example using a sum function and promise syntax | |
// function sum(n1, n2) { | |
// return n1 + n2; | |
// } | |
// thread(sum, 1, 5) | |
// .then(result => thread(sum, result, 1)) | |
// .then(result => console.log('result', result)) | |
// .catch(error => console.error('error', error)); |
@abhishekmatta999 I think there are libraries for doing this, I don't recommend you to use this code as is, it was more of a proof of concept that this was possible, I never used it in production
Can you name some that can be used. And It would be a great help if there is a usage example present.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm getting this error while using your code.
message: "Uncaught ReferenceError: _ref14 is not defined"