Created
June 28, 2017 18:54
-
-
Save tatethurston/f16003fb6c2d3934621e982d39865bd5 to your computer and use it in GitHub Desktop.
Retry jQuery AJAX requests with exponential backoff
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
import $ from 'jquery'; | |
import uuidv4 from 'uuid/v4'; | |
const wait = ms => $.Deferred(defer => setTimeout(defer.resolve, ms)); | |
const request = (opts, numTries = 0) => { | |
/* | |
* Retry failed requests 2 additional times with exponential backoff | |
*/ | |
const RETRY_COUNT = 2; | |
const INITIAL_NETWORK_RETRY_DELAY = 500; | |
const delay = INITIAL_NETWORK_RETRY_DELAY + (INITIAL_NETWORK_RETRY_DELAY * numTries); | |
let idempotencyKey; | |
if (opts.type === 'POST' && !opts.idempotencyKey) { | |
idempotencyKey = uuidv4(); | |
} | |
const options = Object.assign({idempotencyKey}, opts) | |
const $d = $.ajax(options); | |
return $d.then(null, (xhr) => { | |
if (xhr.readyState < 4 && numTries < RETRY_COUNT) { | |
return wait(delay).then(() => request(options, numTries + 1)); | |
} | |
return $d; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing. 🤝