定义一个函数,该函数接受一个函数作为参数,并对该函数执行n次重试



我是一个Javascript新手,试图实现以下目标:

我必须定义一个函数performOperationWithRetry,它以异步函数作为参数,并在try catch块中执行它。如果捕获到错误,则应该再次重试该函数。这种重试应该发生,例如3次之后,它应该只是抛出错误。这个函数performOperationWithRetry应该以同步的方式执行内部函数,并且在所有重试完成之前,代码流不应该继续前进。

await this.performOperationWithRetry(async function(){createS3Folder("xyz")},metrics.s3TrialFailure,0)
async function createS3Folder(key) {
try {console.log(key)
const path = key.toUpperCase()
const Obj = await s3.putObject({
Key: path,
Bucket: envs.bucketName
}).promise();}
catch(err) {
console.log("THROWING_ERR")
throw err
}
}
performOperationWithRetry : async function(func,metric,trialCount) {
try {
console.log("TRIAL ",check)
await func()
}
catch(err) {
if(trialCount == envs.maxRetryCount) {
trialCount = 0;
throw err;
}
else {
trialCount++;
metric.inc(1);
await performOperationWithRetry(func,metric,trialCount)
}
}
}

您所描述的功能可以通过循环简单地实现。可以像调用同步函数一样调用异步函数,只是需要适当地使用asyncawait

async performOperationWithRetry(func, trialCount) {
for (trial = 1; trial <= trialCount; ++trial) {
try {
return await func();
} catch {
// simply ignoring
}
}
}

调用的示例如下:

await this.performOperationWithRetry(() => createS3Folder("xyz"), 3);

现在,您的尝试代码似乎引用了与此特定问题无关的数据(check,envs.maxRetryCount,metric,我不确定这是什么…),所以我怀疑您要实现的实际上是更复杂的。

最新更新