Last active
June 26, 2023 22:59
-
-
Save raineorshine/a933c838e0480962476c509350ed822b to your computer and use it in GitHub Desktop.
A promise that can be resolved on demand.
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 Emitter from 'emitter20' | |
/** Returns a [promise, resolve] pair. The promise is resolved when resolve(value) is called. */ | |
const promiseOnDemand = <T>(): [Promise<T>, (value: T) => void] => { | |
const emitter = new Emitter() | |
const promise = new Promise<T>((resolve, reject) => { | |
emitter.on('resolve', resolve) | |
}) | |
/** Triggers the emitter to resolve the promise. */ | |
const resolve = (value: T) => emitter.trigger('resolve', value) | |
return [promise, resolve] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment