diff --git a/src/index.md b/src/index.md index 6a7563f..b7bc798 100644 --- a/src/index.md +++ b/src/index.md @@ -1,4 +1,3 @@ # Todo -- [ ] retryAsync - [ ] ~~cacheAsync~~ see [memoizee](https://github.com/medikoo/memoizee#memoizing-asynchronous-functions) diff --git a/src/index.ts b/src/index.ts index 73bea99..6bd669d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,4 +2,5 @@ export { default as debounceAsync } from './debounceAsync'; export { default as throttleAsync } from './throttleAsync'; export { default as concurrentAsync } from './concurrentAsync'; export { default as cancelizeAsync } from './cancelizeAsync'; +export { default as withRetryAsync } from './withRetryAsync'; export * from './cancelizeAsync'; diff --git a/src/withRetryAsync/demo.vue b/src/withRetryAsync/demo.vue new file mode 100644 index 0000000..e498604 --- /dev/null +++ b/src/withRetryAsync/demo.vue @@ -0,0 +1,40 @@ + diff --git a/src/withRetryAsync/index.ts b/src/withRetryAsync/index.ts new file mode 100644 index 0000000..0475240 --- /dev/null +++ b/src/withRetryAsync/index.ts @@ -0,0 +1,30 @@ +export default function withRetryAsync( + fn: (this: T, ...p: P) => Promise, + { maxCount = 3, retryInterval = 500 } = {}, +) { + return function withRetryedAsync(this: T, ...args: P): Promise { + return new Promise((resolve, reject) => { + let retriedCount = 0; + // let timer: ReturnType; + const that = this; + + execTask(); + + function execTask() { + console.log('第%d次尝试', retriedCount + 1); + fn.call(that, ...args) + .then((...r) => { + resolve(...r); + }) + .catch((...e) => { + // console.log('failed'); + if (++retriedCount >= maxCount) { + reject(...e); + } else { + setTimeout(execTask, retryInterval); + } + }); + } + }); + }; +} diff --git a/src/withRetryAsync/readme.md b/src/withRetryAsync/readme.md new file mode 100644 index 0000000..ce7bba7 --- /dev/null +++ b/src/withRetryAsync/readme.md @@ -0,0 +1,35 @@ +## Intro + +自动重试。 + +## Demo + +> demo 以网络请求为例,请打开 Devtool 查看效果 + + + + +
+ 查看代码 + +<<< src/withRetryAsync/demo.vue{13,29-34} + +
+ + +## Types + +```ts +export default function withRetryAsync( + fn: (this: T, ...p: P) => Promise, + { + maxCount, + retryInterval, + }?: { + maxCount?: number | undefined; + retryInterval?: number | undefined; + }, +): (this: T, ...args: P) => Promise; +```