index.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. export async function sleep(time: number) {
  2. await new Promise((resolve) => {
  3. setTimeout(() => resolve(null), time);
  4. });
  5. }
  6. export function downloadAsFile(filename: string, content: string) {
  7. const file = new Blob([content], {
  8. type: "text/plain",
  9. });
  10. const fileURL = URL.createObjectURL(file);
  11. downloadUsingAnchor(fileURL, filename);
  12. }
  13. export function downloadUsingAnchor(link: string, name: string) {
  14. const a = document.createElement("a");
  15. a.style.display = "none";
  16. a.href = link;
  17. a.download = name;
  18. document.body.appendChild(a);
  19. a.click();
  20. URL.revokeObjectURL(link);
  21. a.remove();
  22. }
  23. export function isPromise<T>(obj: T | Promise<T>): obj is Promise<T> {
  24. return obj && typeof (obj as any).then === "function";
  25. }
  26. export async function retryAsyncFunction<T>(
  27. request: (abort?: () => void) => Promise<T>,
  28. waitTimeBeforeNextTry?: number[],
  29. ): Promise<T> {
  30. if (!waitTimeBeforeNextTry) waitTimeBeforeNextTry = [2000, 5000, 10000];
  31. for (
  32. let attemptNumber = 0;
  33. attemptNumber <= waitTimeBeforeNextTry.length;
  34. attemptNumber++
  35. ) {
  36. try {
  37. const resp = await request();
  38. return resp;
  39. } catch (e) {
  40. if (attemptNumber === waitTimeBeforeNextTry.length) {
  41. throw e;
  42. }
  43. await sleep(waitTimeBeforeNextTry[attemptNumber]);
  44. }
  45. }
  46. }
  47. export const promiseWithTimeout = async <T>(
  48. request: Promise<T>,
  49. timeout: number,
  50. ): Promise<T> => {
  51. const timeoutRef = { current: null };
  52. const rejectOnTimeout = new Promise<null>((_, reject) => {
  53. timeoutRef.current = setTimeout(
  54. () => reject(new Error("Operation timed out")),
  55. timeout,
  56. );
  57. });
  58. const requestWithTimeOutCancellation = async () => {
  59. const resp = await request;
  60. clearTimeout(timeoutRef.current);
  61. return resp;
  62. };
  63. return await Promise.race([
  64. requestWithTimeOutCancellation(),
  65. rejectOnTimeout,
  66. ]);
  67. };