Last active
August 11, 2021 22:54
-
-
Save mcalavera81/0beafa4a8f0f4d53778abf04ffea06fe to your computer and use it in GitHub Desktop.
exponential back-off algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function getChatRoomWithRetries(id: string, maxDelayMs = 32, maxRetries = 10): Promise<ChatRoom> { | |
return new Promise<ChatRoom>(async (resolve, reject) => { | |
let retryCount = 0; | |
let delayMs = 1000; | |
while (true) { | |
try { | |
return resolve(GetChatRoom({ id })); | |
} catch (e) { | |
if (retryCount++ > maxRetries) return reject(e); | |
await new Promise((resolve) => { | |
let actualDelayMs; | |
if ('Retry-After' in e.response.headers) { // #A | |
actualDelayMs = Number(e.response.headers['Retry-After']) * 1000; | |
} else { | |
actualDelayMs = delayMs + (Math.random() * 1000); // #B | |
} | |
return setTimeout(resolve, actualDelay); | |
}); | |
delayMs *= 2; | |
if (delayMs > maxDelayMs) delayMs = maxDelayMs; | |
} | |
} }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment