Skip to content

Instantly share code, notes, and snippets.

@zshnr
zshnr / async-thread.js
Created February 1, 2020 23:13 — forked from sergiodxa/async-thread.js
Use WebWorkers and promises to run sync heavy functions in a worker (process) and get the result in a promise
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));