Merge remote-tracking branch 'upstream/main' into aeisenberg/ff-refactoring

This commit is contained in:
Andrew Eisenberg 2022-10-12 08:36:16 -07:00
commit 34d48f825c
29 changed files with 185 additions and 89 deletions

View file

@ -863,6 +863,10 @@ export async function tryGetFolderBytes(
* Run a promise for a given amount of time, and if it doesn't resolve within
* that time, call the provided callback and then return undefined.
*
* Important: This does NOT cancel the original promise, so that promise will
* continue in the background even after the timeout has expired. If the
* original promise hangs, then this will prevent the process terminating.
*
* @param timeoutMs The timeout in milliseconds.
* @param promise The promise to run.
* @param onTimeout A callback to call if the promise times out.
@ -873,12 +877,18 @@ export async function withTimeout<T>(
promise: Promise<T>,
onTimeout: () => void
): Promise<T | undefined> {
let finished = false;
const mainTask = async () => {
const result = await promise;
finished = true;
return result;
};
const timeout: Promise<undefined> = new Promise((resolve) => {
setTimeout(() => {
onTimeout();
if (!finished) onTimeout();
resolve(undefined);
}, timeoutMs);
});
return await Promise.race([promise, timeout]);
return await Promise.race([mainTask(), timeout]);
}