memo-promise.ts 604 B

12345678910111213141516171819202122
  1. const notError = Symbol('notError');
  2. export function createMemoizedPromise<T>(fn: () => Promise<T>, preload = true): () => Promise<T> {
  3. let error: Error | typeof notError = notError;
  4. let promise: Promise<T> | null = preload
  5. ? fn().catch(e => {
  6. // Here we record the error so that we can throw it later when the function is called
  7. error = e;
  8. // Here we make sure the Promise still returns the never type
  9. throw e;
  10. })
  11. : null;
  12. return () => {
  13. if (error !== notError) {
  14. return Promise.reject(error);
  15. }
  16. promise ??= fn();
  17. return promise;
  18. };
  19. }