Skip to content

Add retry wrapper example #3

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
69 changes: 69 additions & 0 deletions JavaScript/a-retry-wrapper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
'use strict';

const retry = (options = {}) => {
const {
task = null,
recovery = null,
handleRecovery = false,
tryCount = 3,
} = options;

const errors = [];
let count = 0;

return async (...args) => {
while (count++ < tryCount) {
try {
const res = await task(...args);
return res;
} catch (err) {
errors.push(err);
if (recovery) {
await recovery(...args).catch((err) => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If remove the .catch method from recovery function and use try-catch construction, this wrapper will be compatible with synchronous code

if (!handleRecovery) throw err;
errors.push(err);
});
}
}
}
const finallyError = new Error('To many tries');
throw new AggregateError([...errors, finallyError]);
};
};

// Usage
let targetUrl = 'wrong-url';

const sendRequest = () =>
new Promise((resolve, reject) => {
fetch(targetUrl).then(
(res) => {
console.log('Got response');
resolve(res);
},
(err) => {
console.error('Got error');
reject(err);
},
);
});

const updateUrl = (url) =>
new Promise((resolve, reject) => {
setTimeout(() => {
targetUrl = url;
// reject(new Error('Can not update url'));
console.log('Updated url');
resolve();
}, 1_000);
});

const trySendRequest = retry({
task: sendRequest,
recovery: updateUrl,
handleRecovery: true,
tryCount: 3,
// tryCount: 1,
});

trySendRequest('https://google.com').then(console.log);