Skip to content

Instantly share code, notes, and snippets.

@antlis
Created April 16, 2026 20:07
Show Gist options
  • Select an option

  • Save antlis/927ca000ea10bdc6058f3c3a969edad2 to your computer and use it in GitHub Desktop.

Select an option

Save antlis/927ca000ea10bdc6058f3c3a969edad2 to your computer and use it in GitHub Desktop.
Deduplicates concurrent async calls by sharing a single in-flight Promise. Useful for preventing duplicate network requests or expensive computations.
export function createSharedPromise(fn) {
let promise = null;
return (...args) => {
if (!promise) {
promise = Promise.resolve().then(() => fn(...args)).finally(() => {
promise = null;
});
}
return promise;
};
}
@antlis
Copy link
Copy Markdown
Author

antlis commented Apr 16, 2026

Use case:

const fetchUser = createSharedPromise(() => fetch('/api/user').then(r => r.json()));

// Even if called 5 times simultaneously → only 1 request
await Promise.all([fetchUser(), fetchUser(), fetchUser()]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment