Skip to content

Instantly share code, notes, and snippets.

@qwtel
Last active June 21, 2020 14:27
Show Gist options
  • Save qwtel/24778e0b4a8e7600f2f664c918656051 to your computer and use it in GitHub Desktop.
Save qwtel/24778e0b4a8e7600f2f664c918656051 to your computer and use it in GitHub Desktop.
TS implementation of a promise that can be resolved after it has been created.
type Resolver<T> = (value: T | PromiseLike<T>) => void;
type Rejector = (reason?: any) => void;
type ResolvablePromise<T> = Promise<T> & { resolve: Resolver<T>, reject: Rejector }
export function createResolvablePromise<T>(): ResolvablePromise<T> {
let res: Resolver<T>
let rej: Rejector;
const promise = new Promise((r, s) => (res = r, rej = s)) as ResolvablePromise<T>;
promise.resolve = res;
promise.reject = rej;
return promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment