memo-promise.ts 691 B

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