Last active
July 24, 2019 06:40
-
-
Save murayama/f987b8a5d04d8b042cb2433a9fbf4e2b to your computer and use it in GitHub Desktop.
asyncファンクションで例外が発生したら指定回数リトライする関数
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
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}); |
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
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