mirror of
https://codeberg.org/yeentown/barkey.git
synced 2025-07-07 20:44:34 +00:00
fix: simplify the code
This commit is contained in:
parent
3889457d50
commit
e8f2180279
1 changed files with 14 additions and 28 deletions
|
@ -7,34 +7,20 @@ async function sleep(ms: number): Promise<void> {
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function retryOnThrottled<T>(f: () => Promise<T>, retryCount = 5): Promise<T> {
|
export async function retryOnThrottled<T>(f: () => Promise<T>, retryCount = 5): Promise<T> {
|
||||||
let lastOk = false;
|
let lastError;
|
||||||
let lastResultOrError: T | Error = new Error("No attempt has been done");
|
|
||||||
for (let i = 0; i < Math.min(retryCount, 1); i++) {
|
for (let i = 0; i < Math.min(retryCount, 1); i++) {
|
||||||
const [ok, resultOrError] = await f()
|
try {
|
||||||
.then(result => [true, result])
|
return await f();
|
||||||
.catch(err => [false, err]);
|
} catch (err) {
|
||||||
|
|
||||||
lastOk = ok;
|
|
||||||
lastResultOrError = resultOrError;
|
|
||||||
|
|
||||||
if (ok) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// RATE_LIMIT_EXCEEDED
|
// RATE_LIMIT_EXCEEDED
|
||||||
if (resultOrError?.id === 'd5826d14-3982-4d2e-8011-b9e9f02499ef') {
|
if (err?.id === 'd5826d14-3982-4d2e-8011-b9e9f02499ef') {
|
||||||
await sleep(resultOrError?.info?.fullResetMs ?? 1000);
|
lastError = err;
|
||||||
continue;
|
await sleep(err?.info?.fullResetMs ?? 1000);
|
||||||
}
|
|
||||||
|
|
||||||
// Throw for non-throttling errors
|
|
||||||
throw resultOrError;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (lastOk) {
|
|
||||||
return lastResultOrError as T;
|
|
||||||
} else {
|
} else {
|
||||||
// Give up after getting throttled too many times
|
throw err;
|
||||||
throw lastResultOrError;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw lastError;
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue