Created
October 9, 2025 19:06
-
-
Save wokalek/8fdc31bea233f0811a3d6eca2570095a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export default function<T extends (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>>>(fnAsync: T, { trailing }: { trailing?: boolean } = { trailing: false }) { | |
| let promise: Promise<Awaited<ReturnType<T>>> | undefined | |
| let calledAgain = false | |
| let lastArgs: Parameters<T> | undefined | |
| const deduped = async function (...args: Parameters<T>) { | |
| if (promise) { | |
| calledAgain = true | |
| lastArgs = args | |
| return promise | |
| } | |
| promise = fnAsync(...args) | |
| try { | |
| return await promise | |
| } | |
| finally { | |
| promise = undefined | |
| if (trailing && calledAgain && lastArgs) { | |
| calledAgain = false | |
| /* eslint no-unsafe-finally: "off" */ | |
| return await deduped(...lastArgs as Parameters<T>) | |
| } | |
| } | |
| } as T | |
| return deduped | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment