typescript 通用重试函数装饰器(打字稿)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 通用重试函数装饰器(打字稿)相关的知识,希望对你有一定的参考价值。
export function retrySync<Fun extends (...args: any[]) => any, State>({
fun,
predicate,
nextState,
state
}: {
fun: Fun;
state: State;
nextState: (state: State) => State;
predicate: (state: State) => boolean;
}): Fun {
return function(...args) {
try {
return fun.apply(this, args);
} catch (error) {
if (predicate(state))
return retrySync({
fun,
predicate,
nextState,
state: nextState(state)
});
else throw error;
}
} as any;
}
export function retryAsync<
Fun extends (...args: any[]) => Promise<any>,
State
>({
fun,
predicate,
nextState,
state
}: {
fun: Fun;
state: State;
nextState: (state: State) => State;
predicate: (state: State) => boolean;
}): Fun {
return async function(...args) {
try {
return await fun.apply(this, args);
} catch (error) {
if (await predicate(state))
return retrySync({
fun,
predicate,
nextState,
state: await nextState(state)
});
else throw error;
}
} as any;
}
const greaterThanZero = (n: number) => n > 0;
const decrease = (n: number) => n - 1;
export function retrySyncTimes<Fun extends (...args: any[]) => any>({
times,
fun
}: {
times: number;
fun: Fun;
}) {
return retrySync({
fun,
predicate: greaterThanZero,
nextState: decrease,
state: times
});
}
export function retryAsyncTimes<Fun extends (...args: any[]) => Promise<any>>({
times,
fun
}: {
times: number;
fun: Fun;
}) {
return retryAsync({
fun,
predicate: greaterThanZero,
nextState: decrease,
state: times
});
}
export const retry = {
sync: {
custom: retrySync,
times: retrySyncTimes
},
async: {
custom: retryAsync,
times: retryAsyncTimes
}
};
以上是关于typescript 通用重试函数装饰器(打字稿)的主要内容,如果未能解决你的问题,请参考以下文章
打字稿装饰器和箭头函数
类装饰器上的打字稿文档-返回“类扩展构造函数”的函数
像打字稿一样的飞镖装饰器
带有继承的打字稿装饰器
如何将实例变量传递给打字稿装饰器参数?
打字稿装饰器不能使用箭头函数