Skip to content

Instantly share code, notes, and snippets.

@raineorshine
Last active June 26, 2023 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raineorshine/a933c838e0480962476c509350ed822b to your computer and use it in GitHub Desktop.
Save raineorshine/a933c838e0480962476c509350ed822b to your computer and use it in GitHub Desktop.
A promise that can be resolved on demand.
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