Created
November 28, 2019 13:18
-
-
Save takenoco82/e714d8779614d72778cbfdd21d62034d to your computer and use it in GitHub Desktop.
JavaScriptでリトライ
This file contains 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
const myFunc = () => { | |
return new Promise((resolve, reject) => { | |
if (Math.random() > 0.5) { | |
console.log("resolve"); | |
resolve("OK"); | |
} else { | |
console.log("reject"); | |
reject("Error"); | |
} | |
}) | |
} | |
function sleep(waitSeconds, func) { | |
return new Promise(resolve => { | |
setTimeout(() => { | |
resolve(func()) | |
}, waitSeconds * 1000); | |
}) | |
} | |
function retry({retryCount=3, waitSeconds=1, func}) { | |
let promise = Promise.reject().catch(() => func()); | |
for (let i = 0; i < retryCount; i++) { | |
promise = promise.catch(err => { | |
console.log("Retry:", i + 1); | |
return sleep(waitSeconds, func) | |
}); | |
} | |
return promise; | |
} | |
retry({func: myFunc}).then(result => { | |
console.log("success!", result); | |
}).catch(error => { | |
console.log("failed!", error); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment