Ben Lin
2024-08-20 2e2ec72bdefad3ff51c786721f11b0d8b82d8b1b
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);
    });
};