Skip to content

Instantly share code, notes, and snippets.

@lovetingyuan
Created January 24, 2019 05:07
Show Gist options
  • Save lovetingyuan/1e882c85ccc2b872c7cbaab8f2a8ce97 to your computer and use it in GitHub Desktop.
Save lovetingyuan/1e882c85ccc2b872c7cbaab8f2a8ce97 to your computer and use it in GitHub Desktop.
async run function in a worker
const runAsync = fn => {
const worker = new Worker(
URL.createObjectURL(new Blob([`postMessage((${fn})());`]), {
type: 'application/javascript; charset=utf-8'
})
);
return new Promise((res, rej) => {
worker.onmessage = ({ data }) => {
res(data), worker.terminate();
};
worker.onerror = err => {
rej(err), worker.terminate();
};
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment