Skip to content

Instantly share code, notes, and snippets.

@syusui-s
Created May 25, 2020 13:51
Show Gist options
  • Select an option

  • Save syusui-s/04925e9db5eed8f19258d65e0b888b8a to your computer and use it in GitHub Desktop.

Select an option

Save syusui-s/04925e9db5eed8f19258d65e0b888b8a to your computer and use it in GitHub Desktop.
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