Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs retry function if failed X times

I want my function to execute X(=3) times until success.

In my situation I'm running kinesis.putRecord (from AWS API), and if it fails - I want to run it again until it succeeds, but not more than 3 tries.

I'm new to NodeJS, and the code I wrote smells bad.

const putRecordsPromise = function(params){
    return new Promise((resolve, reject) => {
        kinesis.putRecord(params, function (err, data) {
            resolve(err)
        });
    })
}

async function waterfall(params){
    try{
        let triesCounter = 0;
        while(triesCounter < 2){
            console.log(`try #${triesCounter}`)
            let recordsAnswer = await putRecordsPromise(params)
            if(!recordsAnswer){
                console.log("success")
                break;
            }
            triesCounter += 1;
        }
        // continue ...

    } catch(err){
        console.error(err)
    }
}

waterfall(params)

I promise the err result. Afterwards, If the err is empty, then all good. otherwise, continue running the same command.

I'm sure there is a smarter way to do this. Any help would be appreciated.

like image 945
TheCrystalShip Avatar asked Aug 12 '26 21:08

TheCrystalShip


2 Answers

I think, all the Aws functions can return a Promise out of the box, then you can just put the call into try/catch:

let triesCounter = 0;
while(triesCounter < 2){
    console.log(`try #${triesCounter}`)
    try {
        await kinesis.putRecord(params).promise();
        break;  // 'return' would work here as well
    } catch (err) {
       console.log(err);
    }
    triesCounter ++;
}
like image 169
ttulka Avatar answered Aug 14 '26 11:08

ttulka


In functional style:

...
await tryUntilSucceed(() => kinesis.putRecord(params).promise());
...

async function tryUntilSucceed(promiseFn, maxTries=3) {
    try {
        return await promiseFn();
    } catch (e) {
        if (maxTries > 0) {
            return tryUntilSucceed(promiseFn, maxTries - 1);
        }
        throw e;
    }
}
like image 33
Barney Avatar answered Aug 14 '26 11:08

Barney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!