Skip to content

Instantly share code, notes, and snippets.

@Coutlaw
Last active January 29, 2020 01:38
Show Gist options
  • Save Coutlaw/53224da00bfd87d2b30ca73176d383a2 to your computer and use it in GitHub Desktop.
Save Coutlaw/53224da00bfd87d2b30ca73176d383a2 to your computer and use it in GitHub Desktop.
Recursive retry with exponential backoff in node JS
// A delay function used for our queries
const delay = ms => new Promise(res => setTimeout(res, ms));
// Recursively try the base query when the results are null
// Delay time is 2 seconds and doubles each retry
const baseRetry = ({lead_id}, numberOfRetry = 5, delayMs = 2000) => {
return delay(delayMs).then(() => queryFunction({queryParam}).then((resp = {}) => {
const { potentiallyNullValueFromQuery } = resp;
if(numberOfRetry > 0 && !potentiallNullValueFromQuery ) {
// Retry the query recursively, removing a number of retries remaining
return queryFunction({queryParam}, numberOfRetry - 1, delayMs * 2);
} else {
return resp;
}
}));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment