Skip to content

Commit

Permalink
Config option to cache rejections
Browse files Browse the repository at this point in the history
  • Loading branch information
mupperton committed Oct 10, 2022
1 parent fe5e588 commit 79b88af
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/phunk.ts
@@ -1,5 +1,6 @@
interface Config {
init?: boolean
cacheRejections?: boolean
}

const noop = () => {}
Expand All @@ -13,24 +14,29 @@ class Phunk<T> {
#isResolved = false
#isRejected = false

#cacheRejections

constructor(fn: () => T, config?: Config) {
this.#fn = fn

const options = config ?? {}

this.#cacheRejections = options.cacheRejections === true

if (options.init === true) {
this.next().catch(noop) // catch error to avoid unhandled promise exceptions
}
}

async current() {
if (this.#promise === null) return this.next()
if (!this.#cacheRejections && this.#isRejected) return this.next()

return this.#promise
}

async next() {
if (this.#promise === null || !this.#isResolving) {
if (!this.#isResolving) {
this.#promise = this.#resolve()
}
return this.#promise
Expand Down

0 comments on commit 79b88af

Please sign in to comment.