Skip to content

Commit

Permalink
feat: onRetry
Browse files Browse the repository at this point in the history
  • Loading branch information
bowencool committed Sep 15, 2021
1 parent b2b98a8 commit 893d944
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
10 changes: 8 additions & 2 deletions src/withRetryAsync/demo.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ function getApi(keywords: string) {
method: 'GET',
mode: 'cors',
}).then((res) => {
if (res.status === 200) {
if (res.status >= 200 && res.status < 300) {
return {
data: `result for ${keywords}`,
};
Expand All @@ -18,7 +18,13 @@ function getApi(keywords: string) {
});
}
const autoRetryGetApi = withRetryAsync(getApi);
const autoRetryGetApi = withRetryAsync(getApi, {
maxCount: 3,
retryInterval: 1000,
onRetry(i) {
console.log('第%d次尝试', i + 1);
},
});
export default defineComponent({
setup() {
Expand Down
4 changes: 2 additions & 2 deletions src/withRetryAsync/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export default function withRetryAsync<T, P extends any[], R>(
fn: (this: T, ...p: P) => Promise<R>,
{ maxCount = 3, retryInterval = 500 } = {},
{ maxCount = 3, retryInterval = 500, onRetry = (i: number) => {} } = {},
) {
return function withRetryedAsync(this: T, ...args: P): Promise<R> {
return new Promise((resolve, reject) => {
Expand All @@ -11,7 +11,7 @@ export default function withRetryAsync<T, P extends any[], R>(
execTask();

function execTask() {
console.log('第%d次尝试', retriedCount + 1);
onRetry(retriedCount);
fn.call(that, ...args)
.then((...r) => {
resolve(...r);
Expand Down

0 comments on commit 893d944

Please sign in to comment.