index.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { wait } from "@/utils/promise";
  2. export function downloadAsFile(filename: string, content: string) {
  3. const file = new Blob([content], {
  4. type: "text/plain",
  5. });
  6. const fileURL = URL.createObjectURL(file);
  7. downloadUsingAnchor(fileURL, filename);
  8. }
  9. export function downloadUsingAnchor(link: string, name: string) {
  10. const a = document.createElement("a");
  11. a.style.display = "none";
  12. a.href = link;
  13. a.download = name;
  14. document.body.appendChild(a);
  15. a.click();
  16. URL.revokeObjectURL(link);
  17. a.remove();
  18. }
  19. export function isPromise<T>(obj: T | Promise<T>): obj is Promise<T> {
  20. return obj && typeof (obj as any).then === "function";
  21. }
  22. export async function retryAsyncFunction<T>(
  23. request: (abort?: () => void) => Promise<T>,
  24. waitTimeBeforeNextTry?: number[],
  25. ): Promise<T> {
  26. if (!waitTimeBeforeNextTry) waitTimeBeforeNextTry = [2000, 5000, 10000];
  27. for (
  28. let attemptNumber = 0;
  29. attemptNumber <= waitTimeBeforeNextTry.length;
  30. attemptNumber++
  31. ) {
  32. try {
  33. const resp = await request();
  34. return resp;
  35. } catch (e) {
  36. if (attemptNumber === waitTimeBeforeNextTry.length) {
  37. throw e;
  38. }
  39. await wait(waitTimeBeforeNextTry[attemptNumber]);
  40. }
  41. }
  42. }