Created
December 7, 2021 11:09
-
-
Save ashwynh21/4143c13310a37f69da3ea2e2511b2b1d to your computer and use it in GitHub Desktop.
A class modelled from the Completer in dart, that has promise functionality but also allows external resolution and rejection without the need for scoping
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
/* | |
* completer - | |
* | |
* the definition of this class mimics the functionality of the completer class that we have defined in the dart | |
* packages that lets you deal with unscoped promises instances that can be rejected and resolved in any part of the | |
* application so long as you are able to pass the reference to the context properly | |
* */ | |
type Resolvable<T> = T | PromiseLike<T>; | |
export class Completer<T> { | |
public promise: Promise<T>; | |
// we have to type assert here | |
public resolve!: (value: Resolvable<T>) => void; | |
public reject!: (reason?: any) => void; | |
constructor(options?: { timeout?: number; error?: Error }) { | |
this.promise = new Promise((resolve, reject) => { | |
this.resolve = resolve; | |
this.reject = reject; | |
}); | |
if (options) { | |
if (options.timeout) { | |
setTimeout(() => { | |
if (options.error) { | |
return this.reject(options.error); | |
} | |
return this.reject(new Error('Completer timeout error')); | |
}, options.timeout); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment