Skip to content

Instantly share code, notes, and snippets.

@osartun
Created July 1, 2019 16:02
Show Gist options
  • Save osartun/e7ddae8619b4f5bbfd2b7ebe90f0af19 to your computer and use it in GitHub Desktop.
Save osartun/e7ddae8619b4f5bbfd2b7ebe90f0af19 to your computer and use it in GitHub Desktop.
Code graveyard
describe('promiseRetry', () => {
it('resolves immediately if successful', async () => {
const expectedValue = 'Expected Value'
const promiseFn = jest.fn().mockResolvedValue(expectedValue)
const result = await promiseRetry(promiseFn)
expect(promiseFn).toHaveBeenCalledTimes(1)
expect(result).toBe(expectedValue)
})
it('retries if unsuccessful', async () => {
const expectedValue = 'Expected Value'
const promiseFn = jest
.fn()
.mockResolvedValue(expectedValue)
.mockRejectedValueOnce(new Error('Some error'))
const result = await promiseRetry(promiseFn)
expect(promiseFn).toHaveBeenCalledTimes(2)
expect(result).toBe(expectedValue)
})
it('fails if continuously unsuccessful', async () => {
const expectedError = new Error('Some error')
const promiseFn = jest.fn().mockRejectedValue(expectedError)
expect(promiseRetry(promiseFn)).rejects.toEqual(expectedError)
})
})
// Really basic, no-dependency promiseRetry implementation
export const promiseRetry = (
promiseFn: () => Promise<unknown>,
options: PromiseRetryOptions = {}
) => {
const { retries = 5 } = options
const retry = (
fn: () => Promise<unknown>,
remainingAttempts: number,
resolve: (value?: unknown) => void,
reject: (reason?: unknown) => void
) => {
fn()
.then(resolve)
.catch((err: Error) => {
if (remainingAttempts <= 0) {
return reject(err)
}
return retry(fn, --remainingAttempts, resolve, reject)
})
}
return new Promise((resolve, reject) => {
retry(promiseFn, retries - 1, resolve, reject)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment