Created
February 18, 2019 19:42
-
-
Save GirlBossRush/2933306ec17586ba55026b28056706d4 to your computer and use it in GitHub Desktop.
nonced 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
import id from './generate-id' | |
export type NoncedEventPayload = { | |
nonce: string | |
} | |
export type ParsedEventPayload = NoncedEventPayload & { | |
value: string | |
error: Error | null | |
} | |
export function createNoncedPromise<T extends ParsedEventPayload>(worker: Worker, payload: NoncedEventPayload) { | |
const nonce = id(8) | |
return new Promise<T>((resolve, reject) => { | |
function onMessage(event: MessageEvent) { | |
const data: T = event.data | |
if (data.nonce !== nonce) return | |
worker.removeEventListener('message', onMessage) | |
if (data.error) { | |
reject(data) | |
} else { | |
resolve(data) | |
} | |
} | |
worker.addEventListener('message', onMessage) | |
worker.postMessage(payload) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment