1

I am very new to Javascript and trying to achieve the following.

I have to define a function performOperationWithRetry which takes an asynchronous function as a parameter and performs it in a try catch block. If an error is caught, it should retry the function again. This retry should happen, for example for 3 times after which it should just throw error. This function performOperationWithRetryshould perform the inner function in a synchronous way and the code flow should not move ahead until all retries are done. Here is my attempt at achieving the same, which does not work.

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)
            }
        }
    }
Sarthak
  • 188
  • 1
  • 2
  • 14

1 Answers1

0

The functionality you describe can be simply achieved with a loop. An asynchronous function can be invoked just like a synchronous one, except that you need to use async and await appropriately.

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

an exemple invocation would be like:

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

Now, your attempt code seems to be referencing data extraneous to this specific problem (check, envs.maxRetryCount, metric, I'm not sure what this is all for...), so I suspect what you are trying to achieve is actually more sophisticated.

GOTO 0
  • 42,323
  • 22
  • 125
  • 158