Last active
March 6, 2021 02:15
-
-
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
This file contains 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
/* 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