Skip to content

Commit

Permalink
Cache pending promises (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
LinusU authored and sindresorhus committed Oct 11, 2017
1 parent 009ce6a commit 2189e3c
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 11 deletions.
12 changes: 4 additions & 8 deletions index.js
Expand Up @@ -40,15 +40,11 @@ module.exports = (fn, opts) => {
});
};

setData(key, ret);

if (isPromise(ret) && opts.cachePromiseRejection === false) {
// Only cache resolved promises unless `cachePromiseRejection` is set to `true`
ret
.then(() => {
setData(key, ret);
})
.catch(() => {});
} else {
setData(key, ret);
// Remove rejected promises from cache unless `cachePromiseRejection` is set to `true`
ret.catch(() => cache.delete(key));
}

return ret;
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Expand Up @@ -104,7 +104,7 @@ You could for example change it to only cache on the first argument `x => JSON.s
Type: `Object`<br>
Default: `new Map()`

Use a different cache storage. Must implement the following methods: `.has(key)`, `.get(key)`, `.set(key, value)`, and optionally `.clear()`. You could for example use a `WeakMap` instead or [`quick-lru`](https://github.com/sindresorhus/quick-lru) for a LRU cache.
Use a different cache storage. Must implement the following methods: `.has(key)`, `.get(key)`, `.set(key, value)`, `.delete(key)`, and optionally `.clear()`. You could for example use a `WeakMap` instead or [`quick-lru`](https://github.com/sindresorhus/quick-lru) for a LRU cache.

##### cachePromiseRejection

Expand Down
10 changes: 8 additions & 2 deletions test.js
Expand Up @@ -87,8 +87,14 @@ test('do not cache rejected promises', async t => {
});

await t.throws(memoized(), 'foo bar');
t.is(await memoized(), 2);
t.is(await memoized(), 2);

const first = memoized();
const second = memoized();
const third = memoized();

t.is(await first, 2);
t.is(await second, 2);
t.is(await third, 2);
});

test('cache rejected promises if enabled', async t => {
Expand Down

0 comments on commit 2189e3c

Please sign in to comment.