Created
May 25, 2020 13:51
-
-
Save syusui-s/04925e9db5eed8f19258d65e0b888b8a to your computer and use it in GitHub Desktop.
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
| const sleep = (ms: number) : Promise<unknown> => new Promise(resolve => setTimeout(resolve, ms)); | |
| const retry = async <Args extends any[], Result>( | |
| count: number, | |
| interval: number, | |
| fn: (...args: Args) => Promise<Result>, | |
| ...args: Args | |
| ) => { | |
| for (let i = 0; i < count; ++i) { | |
| const result = await fn(...args); | |
| if (result) | |
| return result; | |
| await sleep(interval); | |
| } | |
| throw new TypeError(`function execution failed: ${fn}(${args}) (${count} times, interval ${interval} ms)`); | |
| }; | |
| let count = 0; | |
| retry( | |
| 10, | |
| 100, | |
| async (test: string, fuga: string) => { | |
| count += 1; | |
| console.log(count); | |
| return count === 15; | |
| }, | |
| "hoge", | |
| "aaa", | |
| "aaa", // <----- this line causes error because function receives 2 parameters but more arguments are given | |
| "aaa", | |
| "aaa", | |
| "aaa", | |
| ) | |
| .then(() => console.log("ok")) | |
| .catch(err => console.log(`fail ${err}`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment