Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] Handle async onRetry #50

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ retry(retrier : Function, opts : Object) => Promise
* `maxTimeout`: The maximum number of milliseconds between two retries. Default is `Infinity`.
* `randomize`: Randomizes the timeouts by multiplying with a factor between `1` to `2`. Default is `false`.
* `onRetry`: an optional `Function` that is invoked after a new retry is performed. It's passed the `Error` that triggered it as a parameter.

* `awaitOnRetry`: An optional flag to wait for `onRetry` to resolve before retrying.

## Authors

- Guillermo Rauch ([@rauchg](https://twitter.com/rauchg)) - [ZEIT](https://zeit.co)
Expand Down
13 changes: 12 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,18 @@ function retry(fn, opts) {
return;
}

if (!op.retry(err)) {
if (
options.awaitOnRetry &&
options.onRetry &&
err &&
num <= options.retries
) {
Promise.resolve(options.onRetry(err, num)).then(() => {
if (!op.retry(err)) {
reject(op.mainError());
}
});
} else if (!op.retry(err)) {
reject(op.mainError());
} else if (options.onRetry) {
options.onRetry(err, num);
Expand Down
2 changes: 1 addition & 1 deletion now.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"type": "static"
"version": 2
}
27 changes: 21 additions & 6 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,16 +116,31 @@ test('with number of retries', async t => {
try {
await retry(() => fetch('https://www.fakewikipedia.org'), {
retries: 2,
onRetry: (err, i) => {
if (err) {
// eslint-disable-next-line no-console
console.log('Retry error : ', err);
}

onRetry: (_, i) => {
retries = i;
}
});
} catch (err) {
t.deepEqual(retries, 2);
}
});

test('wait for async onRetry', async t => {
const timeout = 1000;
let before;
let after;

try {
await retry(() => fetch('https://www.fakewikipedia.org'), {
retries: 2,
awaitOnRetry: true,
onRetry: async () => {
before = Date.now();
await sleep(timeout);
after = Date.now();
}
});
} catch (err) {
t.is(after - before >= timeout, true);
}
});