Ben Lin
2025-03-07 ce374a9f4920a2d0e5ebe81a9872436088db6d55
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
type CachedKey = string | number;
 
const cachePromise = new Map<CachedKey, Promise<any>>();
 
export const getCachePromise = (cacheKey: CachedKey) => {
  return cachePromise.get(cacheKey);
};
 
export const setCachePromise = (cacheKey: CachedKey, promise: Promise<any>) => {
  // Should cache the same promise, cannot be promise.finally
  // Because the promise.finally will change the reference of the promise
  cachePromise.set(cacheKey, promise);
 
  // no use promise.finally for compatibility
  promise
    .then((res) => {
      cachePromise.delete(cacheKey);
      return res;
    })
    .catch(() => {
      cachePromise.delete(cacheKey);
    });
};