Last active
July 14, 2023 00:31
-
-
Save 1eedaegon/af2f2e2be38c0193d39b1fce5cb97b40 to your computer and use it in GitHub Desktop.
Flow control(Multi threading): Web worker + Promise for Inversion of Control
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
| // 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