Skip to content
JavaScript: Remove failed promises from a lookup cache

JavaScript: Remove failed promises from a lookup cache

November 19, 2026

Caching a promise lets simultaneous lookups share one load. If that promise rejects and stays in the cache, later callers receive the same failure without trying again. Remove a failed entry before propagating its error.

Set up

Tested on Debian 13 Linux with Node.js v24.19.0. Use Bash, Node.js on your PATH, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal through cleanup. Stop if setup fails before saving the source.

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save as javascript-evict-rejected-promise-cache.mjs:

import assert from 'node:assert/strict';

function memoizeLoads(load) {
  const cache = new Map();
  return key => {
    if (cache.has(key)) return cache.get(key);
    const pending = Promise.resolve().then(() => load(key)).catch(error => {
      cache.delete(key);
      throw error;
    });
    cache.set(key, pending);
    return pending;
  };
}

let attempts = 0;
const lookup = memoizeLoads(async key => {
  attempts++;
  if (attempts === 1) throw new Error('temporary failure');
  return `value:${key}`;
});
const first = lookup('guide');
const shared = lookup('guide');
assert.equal(first, shared);
const failures = await Promise.allSettled([first, shared]);
assert.deepEqual(failures.map(result => result.status), ['rejected', 'rejected']);
assert.equal(attempts, 1);
const retry = lookup('guide');
assert.notEqual(retry, first);
assert.equal(await retry, 'value:guide');
assert.equal(lookup('guide'), retry);
assert.equal(attempts, 2);
assert.equal(await lookup('faq'), 'value:faq');
assert.equal(attempts, 3);

let synchronousAttempts = 0;
const syncLookup = memoizeLoads(() => {
  synchronousAttempts++;
  if (synchronousAttempts === 1) throw new Error('synchronous failure');
  return undefined;
});
await assert.rejects(syncLookup('optional'), /synchronous failure/);
assert.equal(await syncLookup('optional'), undefined);
assert.equal(await syncLookup('optional'), undefined);
assert.equal(synchronousAttempts, 2);
console.log('Initial requests shared one failed load');
console.log('Retry value:', await retry);
console.log('Attempts after another key:', attempts);
console.log('Synchronous failure and cached undefined: passed');

Run:

node javascript-evict-rejected-promise-cache.mjs

Observed output:

Initial requests shared one failed load
Retry value: value:guide
Attempts after another key: 3
Synchronous failure and cached undefined: passed

Store the promise before starting the load

The wrapper puts the pending promise in the Map before the loader runs. Two immediate calls for the same key therefore receive the same promise. The first load intentionally fails, and both callers observe that rejection. A later call starts a new load and succeeds.

Starting the loader in a promise callback also turns a synchronous throw into a rejection. The second fixture tests that path and verifies that undefined can be cached as a successful result. Cache membership is checked separately from the value.

The rejection handler deletes the entry and throws the original error. Under the ECMAScript promise catch rules, the returned promise remains rejected when that handler throws. Each caller must still handle its returned promise; removing the cache entry does not make a failure successful.

Choose the remaining cache policies

This example retains successful loads indefinitely and shares their resolved values. It suits the fixed primitive values in the test. Mutable objects would also be shared, so decide whether callers may edit them or should receive copies.

The helper has no expiration, size bound or automatic retry loop. A retry happens only when another lookup arrives after a failure. A permanently pending load also stays cached; timeouts and cancellation require a separate policy. The cache is local to one wrapper in one process and does not coordinate other workers.

The cache is private and has no replacement or invalidation API. If you add one, ensure an older failing load cannot delete a newer entry for the same key. The loader must not await another call to this wrapper for its own key, which would make the load depend on itself.

Clean up

Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.

rm -- javascript-evict-rejected-promise-cache.mjs
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

Acknowledgements

This post was created with assistance from AI.

Last updated on