Comment Comment by ralusek I have written many tools that do something like this, very useful.Just gotta be careful with memory leaks, so (for a TS example) you might want to do something like this: const promiseMap<key, Promise<any>> = new Map(); async function keyedDebounce<R>(key: string, fn: () => R) { const existingPromise = promiseMap.get(key); if (existingPromise) return existingPromise; const promise = new Promise(async (resolve) => { const result = await fn(); // ignore lack of error handling // avoid memory leak by cleaning up promiseMap.delete(key); // this will call the .then or awaited promises everywhere resolve(result); }); promiseMap.set(key, promise); return promise; } So that the promise sticks around for that key while the function is active, but then it clears it so that you're not just building up keys in a map. parent ralusek 4 years ago
Just gotta be careful with memory leaks, so (for a TS example) you might want to do something like this:
So that the promise sticks around for that key while the function is active, but then it clears it so that you're not just building up keys in a map.