Last active
April 4, 2018 02:02
-
-
Save gf3/25522ed3f60e389cb01c to your computer and use it in GitHub Desktop.
Backoff AJAX requests
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
/** | |
* @flow | |
*/ | |
import request from 'lib/request'; | |
type F<T> = (response: T) => bool; | |
const BACKOFF_MAX = 60; // seconds | |
const BACKOFF_ATTEMPTS = 60; | |
function decay(count: number): number { | |
if (count <= 0) { | |
return 0; | |
} | |
return Math.min(BACKOFF_MAX, count * 1.4); | |
} | |
export function backoff<R>(predicate: F<R>, args: Object): { cancel: () => void, promise: Promise<R> } { | |
let isCancelled = false; | |
const promise = new Promise((resolve, reject) => { | |
let attempts = 0; | |
let backoffValue = 1; | |
function run() { | |
attempts += 1; | |
request(args).then(response => { | |
if (predicate(response)) { | |
return resolve(response); | |
} | |
else if (isCancelled == true) { | |
return reject({ isCancelled }); | |
} | |
reRun(); | |
}, error => { | |
if (attempts === BACKOFF_ATTEMPTS) { | |
return reject(error); | |
} | |
else if (isCancelled == true) { | |
return reject({ isCancelled }); | |
} | |
reRun(); | |
}); | |
} | |
function reRun() { | |
backoffValue = decay(backoffValue); | |
setTimeout(run, backoffValue * 1000); | |
} | |
run(); | |
}); | |
return { | |
cancel() { | |
isCancelled = true; | |
}, | |
promise | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment