Skip to content

Commit

Permalink
Fix consecutive non awaited calls (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
krystofwoldrich committed Sep 19, 2021
1 parent 34ebc0c commit 343ac6e
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 15 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ jobs:
matrix:
node-version:
- 16
- 14
- 12
- 10
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
Expand Down
28 changes: 14 additions & 14 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,24 +22,24 @@ const pMemoize = (fn, {cachePromiseRejection = false, ...options} = {}) => {
return cacheItem.data;
}

const result = fn.apply(this, arguments_);
const promise = fn.apply(this, arguments_);
cache.set(key, {
data: promise,
maxAge: Number.POSITIVE_INFINITY
});

let resultError;
try {
return await Promise.resolve(result);
} catch (error) {
resultError = error;
throw error;
} finally {
const [{reason}] = await Promise.allSettled([promise]);
if (!cachePromiseRejection && reason) {
cache.delete(key);
} else if (maxAge) {
// Promise fulfilled, so start the timer
cache.set(key, {
data: result,
maxAge: maxAge ? Date.now() + maxAge : Number.POSITIVE_INFINITY
data: promise,
maxAge: Date.now() + maxAge
});

if (!cachePromiseRejection && resultError) {
cache.delete(key);
}
}

return promise;
};

mimicFn(memoized, fn);
Expand Down
12 changes: 12 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ test('main', async t => {
t.is(await memoized(10), 1);
});

test('does memoize consecutive calls', async t => {
let i = 0;
const memoized = pMemoize(async () => i++);
const firstCall = memoized();
const secondCall = memoized();

await Promise.all([firstCall, secondCall]);

t.is(await firstCall, 0);
t.is(await secondCall, 0);
});

test('does not memoize rejected promise', async t => {
let i = 0;

Expand Down

0 comments on commit 343ac6e

Please sign in to comment.