Created
July 1, 2019 16:02
-
-
Save osartun/e7ddae8619b4f5bbfd2b7ebe90f0af19 to your computer and use it in GitHub Desktop.
Code graveyard
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
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) | |
}) | |
}) |
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
// 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