Skip to content

Commit

Permalink
fix: remove cache promise when resolved
Browse files Browse the repository at this point in the history
  • Loading branch information
ph-fritsche committed Sep 3, 2021
1 parent daec12e commit 637991e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
13 changes: 10 additions & 3 deletions src/methods/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,19 +101,26 @@ export function get<
}
})

for (const key of hit) {
delete cache[key].promise
}

dispatch(cache, hit)

const loaderPromise = typeof loader === 'function' ? loader(stillMissing) : undefined

if (loaderPromise) {
stillMissing.forEach(key => {
for (const key of stillMissing) {
cache[key].promise = loaderPromise.then(() => cache[key].obj)
loaderPromise.finally(() => { delete cache[key].promise })
})
}

return missing.map(key => stillMissing.includes(key) ? cache[key].promise : cache[key].obj)
} else {
stillMissing.forEach(key => { delete cache[key].promise })
for (const key of stillMissing) {
delete cache[key].promise
}

return missing.map(key => cache[key].obj)
}
},
Expand Down
23 changes: 23 additions & 0 deletions test/methods/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,26 @@ it('skip fetching object when a promise is pending', async () => {
await new Promise(r => setTimeout(r, 2))
expect(loader).toBeCalledTimes(2)
})

it('remove promise when resolved', async () => {
const { api, cache } = await setupApi({cacheValues: {foo: 123}, idbValues: {bar: 456}})
let resolveLoader: () => void = () => { return }
const loader = jest.fn(() => new Promise<void>(r => { resolveLoader = r}))

expect(api.get(['foo', 'bar', 'baz'], loader)).toEqual({foo: 123, bar: undefined, baz: undefined})
expect(cache.foo.promise).toBe(undefined)
expect(cache.bar.promise).toBeInstanceOf(Promise)
expect(cache.baz.promise).toBeInstanceOf(Promise)

await new Promise(r => setTimeout(r, 2))

expect(cache.bar.promise).toBe(undefined)
expect(cache.baz.promise).toBeInstanceOf(Promise)

resolveLoader()
await new Promise(r => setTimeout(r, 2))

expect(cache.foo.promise).toBe(undefined)
expect(cache.bar.promise).toBe(undefined)
expect(cache.baz.promise).toBe(undefined)
})

0 comments on commit 637991e

Please sign in to comment.