Last active
October 25, 2019 11:56
-
-
Save DimosthenisK/f5ca58d4bf661a2fce7ccf3490591cf0 to your computer and use it in GitHub Desktop.
Axios Request Retry function - ES7 implementation of axios request retry
This file contains hidden or 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
/** | |
Asynchronous Recursive Request retry with Axios | |
Author: Dimosthenis Kalaitzis <[email protected]> | |
Requires Axios | |
Throws error after failing all available attempts | |
@param requestParams AxiosRequestOptions | |
@param attempts number | |
*/ | |
async sendRequest(requestParams, attempts = 0) { | |
let maximumTimeouts = 20; //Maximum attempts, don't set too high or you may risk high memory usage | |
let minimumWaitBeforeTimeout = 50; //In milliseconds | |
let waitBeforeTimeoutVariation = 1000; //In milliseconds | |
//Timeout Implementation | |
const timeout = ms => new Promise(res => setTimeout(res, ms)); | |
//Attempt handling - don't forget to wrap in try catch to catch the error | |
attempts++; | |
if (attempts > maximumTimeouts) throw new Error("Request failed after retrying"); | |
console.log("Attempt #" + attempts); | |
try { | |
if (attempts > 1) { //No reason to wait before send on the first try | |
await timeout(Math.random() * waitBeforeTimeoutVariation + minimumWaitBeforeTimeout); | |
} | |
let response = await axios.request(requestParams); | |
return response; | |
} | |
catch (err) { //Axios throws an error on all non-200 code responses, so we handle them here | |
return await this.sendRequest(url, attempts); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment