From aead60f6782f30d52ec9f14caccbec68f745fd66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20Unneb=C3=A4ck?= Date: Thu, 28 Sep 2017 17:55:28 +0100 Subject: [PATCH] Cache pending promises --- index.js | 12 ++++-------- readme.md | 2 +- test.js | 10 ++++++++-- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/index.js b/index.js index 9a67ae8..ad49270 100644 --- a/index.js +++ b/index.js @@ -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; diff --git a/readme.md b/readme.md index 749d361..ee9d89e 100644 --- a/readme.md +++ b/readme.md @@ -104,7 +104,7 @@ You could for example change it to only cache on the first argument `x => JSON.s Type: `Object`
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 diff --git a/test.js b/test.js index 77c6e9c..d4b06d6 100644 --- a/test.js +++ b/test.js @@ -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 => {