mirror of
https://github.com/ente-io/ente.git
synced 2025-05-24 12:09:17 +00:00
78 lines
2.1 KiB
TypeScript
78 lines
2.1 KiB
TypeScript
/**
|
|
* Wait for {@link ms} milliseconds
|
|
*
|
|
* This function is a promisified `setTimeout`. It returns a promise that
|
|
* resolves after {@link ms} milliseconds.
|
|
*/
|
|
export async function sleep(ms: number) {
|
|
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
|
|
export function downloadAsFile(filename: string, content: string) {
|
|
const file = new Blob([content], {
|
|
type: "text/plain",
|
|
});
|
|
const fileURL = URL.createObjectURL(file);
|
|
downloadUsingAnchor(fileURL, filename);
|
|
}
|
|
|
|
export function downloadUsingAnchor(link: string, name: string) {
|
|
const a = document.createElement("a");
|
|
a.style.display = "none";
|
|
a.href = link;
|
|
a.download = name;
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
URL.revokeObjectURL(link);
|
|
a.remove();
|
|
}
|
|
|
|
export function isPromise<T>(obj: T | Promise<T>): obj is Promise<T> {
|
|
return obj && typeof (obj as any).then === "function";
|
|
}
|
|
|
|
export async function retryAsyncFunction<T>(
|
|
request: (abort?: () => void) => Promise<T>,
|
|
waitTimeBeforeNextTry?: number[],
|
|
): Promise<T> {
|
|
if (!waitTimeBeforeNextTry) waitTimeBeforeNextTry = [2000, 5000, 10000];
|
|
|
|
for (
|
|
let attemptNumber = 0;
|
|
attemptNumber <= waitTimeBeforeNextTry.length;
|
|
attemptNumber++
|
|
) {
|
|
try {
|
|
const resp = await request();
|
|
return resp;
|
|
} catch (e) {
|
|
if (attemptNumber === waitTimeBeforeNextTry.length) {
|
|
throw e;
|
|
}
|
|
await sleep(waitTimeBeforeNextTry[attemptNumber]);
|
|
}
|
|
}
|
|
}
|
|
|
|
export const promiseWithTimeout = async <T>(
|
|
request: Promise<T>,
|
|
timeout: number,
|
|
): Promise<T> => {
|
|
const timeoutRef = { current: null };
|
|
const rejectOnTimeout = new Promise<null>((_, reject) => {
|
|
timeoutRef.current = setTimeout(
|
|
() => reject(new Error("Operation timed out")),
|
|
timeout,
|
|
);
|
|
});
|
|
const requestWithTimeOutCancellation = async () => {
|
|
const resp = await request;
|
|
clearTimeout(timeoutRef.current);
|
|
return resp;
|
|
};
|
|
return await Promise.race([
|
|
requestWithTimeOutCancellation(),
|
|
rejectOnTimeout,
|
|
]);
|
|
};
|