Skip to content

Instantly share code, notes, and snippets.

@1eedaegon
Last active July 14, 2023 00:31
Show Gist options
  • Select an option

  • Save 1eedaegon/af2f2e2be38c0193d39b1fce5cb97b40 to your computer and use it in GitHub Desktop.

Select an option

Save 1eedaegon/af2f2e2be38c0193d39b1fce5cb97b40 to your computer and use it in GitHub Desktop.
Flow control(Multi threading): Web worker + Promise for Inversion of Control
// Warning!: It is not yet prevented for race condition!
const mine = { js: { type: 'application/javascript' } };
const WorkerPromise = f => {
let resolve;
let reject;
const worker = Object.assign(
new Worker(
URL.createObjectURL(
new Blob([`onmessage = e => postMessage((${f})(e.data));`], mine.js),
),
),
{ onmessage: e => resolve(e.data), onerror: e => reject(e.data) },
);
return data =>
new Promise((res, rej) => {
resolve = res;
reject = rej;
worker.postMessage(data);
});
};
export default WorkerPromise;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment