Skip to content

Instantly share code, notes, and snippets.

@myobie
Created August 2, 2021 15:09
Embed
What would you like to do?
My own promise-like object where I can type the rejection and I can resolve from the outside
export class Deferred<T = void, E = Error> {
#promise: Promise<T>
// deno-lint-ignore ban-ts-comment
// @ts-ignore
resolve: (arg: T) => void
// deno-lint-ignore ban-ts-comment
// @ts-ignore
reject: (arg: E) => void
constructor() {
this.#promise = new Promise<T>((res, rej) => {
this.resolve = res
this.reject = rej
})
}
then<F, R>(onFulfilled: (arg: T) => F, onRejected?: (arg: E) => R) {
return this.#promise.then(onFulfilled, onRejected)
}
catch<F>(cb: (arg: E) => F) {
return this.#promise.catch(cb)
}
finally(cb: () => void) {
return this.#promise.finally(cb)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment