Skip to content

Instantly share code, notes, and snippets.

@murayama
Last active July 24, 2019 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save murayama/f987b8a5d04d8b042cb2433a9fbf4e2b to your computer and use it in GitHub Desktop.
Save murayama/f987b8a5d04d8b042cb2433a9fbf4e2b to your computer and use it in GitHub Desktop.
asyncファンクションで例外が発生したら指定回数リトライする関数
retry(async (abort, num) => {
const res = fetch('https://xxxx').then(res => res.json());
if (condition) {
// 特定の条件の場合にリトライをしないで処理を抜ける場合はabortをコールする
abort(new Error('error message'));
}
}, {retryMax: 3, sleep: 300});
export const retry = (fn, option = {retryMax: 2, sleep: null}) => {
let retryCount = 0;
let aborted = false;
const run = (resolve, reject) => {
const abort = err => {
aborted = true;
reject(err || new Error('Aborted.'));
};
const onError = err => {
if (!aborted) {
if (retryCount < option.retryMax) {
retryCount++;
runAttempt();
return;
} else {
reject(err);
}
}
};
const runAttempt = async () => {
if (retryCount > 0 && option.sleep) {
await sleep();
}
fn(abort, retryCount)
.then(resolve)
.catch(onError);
};
runAttempt();
};
const sleep = () => {
return new Promise((resolve, reject) => {
console.log(`retry sleep ${option.sleep}`);
setTimeout(() => resolve(), option.sleep);
});
};
return new Promise(run);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment