Skip to content

Instantly share code, notes, and snippets.

@kaisermann
Last active March 6, 2021 02:15
Show Gist options
  • Save kaisermann/c5f4566ec709ed8f5586cac7d11cd690 to your computer and use it in GitHub Desktop.
Save kaisermann/c5f4566ec709ed8f5586cac7d11cd690 to your computer and use it in GitHub Desktop.
Creates a promise that can be resolved or reject from outside of its scope
/* eslint-disable @typescript-eslint/no-explicit-any */
type Reject = (reason?: any) => void
type Resolve<T> = (val: T | PromiseLike<T>) => void
export interface ControlledPromise<T> extends Promise<T> {
reject: Reject
resolve: Resolve<T>
}
function noop() {}
/**
* Returns a controlled promise, a promise with two additional properties:
* 'resolve' and 'reject'
*/
export function getControlledPromise<T = unknown>() {
let resolve: Resolve<T> = noop
let reject: Reject = noop
const bag = new Promise((res, rej) => {
resolve = res
reject = rej
}) as ControlledPromise<T>
bag.resolve = resolve
bag.reject = reject
return bag as ControlledPromise<T>
}
// ...
async function main() {
const controlledPromise = getControlledPromise()
setTimeout(() => controlledPromise.resolve('potato'), 3000)
const result = await controlledPromise
console.log(result) // prints "potato" after three seconds
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment