Skip to content

Instantly share code, notes, and snippets.

@myobie
Created August 2, 2021 15:09
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 myobie/cccef7d7afff392ce4bed7360abf83e4 to your computer and use it in GitHub Desktop.
Save myobie/cccef7d7afff392ce4bed7360abf83e4 to your computer and use it in GitHub Desktop.
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