abduakhatov
abduakhatov

Reputation: 23

Custom Retry Function

Trying to create a function retry that returns a function that calls and returns value from callback function passing its arguments and catches errors. If error is caught it should return the callback function with catch. If number of errors exceeds count then throw an Error.

Here is what was done so far:

const retry = (count, callback) => {
    let attempts = 1;
    const _retry = async (...args) => callback(...args)
        .catch(err => {
            if (attempts > count) throw err
            attempts++
            return _retry(...args)
        });
    return _retry
}

The problem appears when called:

var r = Math.random().toString(36).slice(2)
var arg = (n) => async (...v) =>
    --n < 0 ? v : Promise.reject(Error(`>>> x:${v}`))
    
await retry(3, arg(2))(r)

Upvotes: 2

Views: 637

Answers (1)

elemetrics
elemetrics

Reputation: 340

It looks to me like retry returns a Promise right now, due to the async keyword. Try dropping the async keyword from the retry definition and make the _retry function async:

const retry = (count, callback) => {
    let attempts = 1;
    return _retry = async (...args) => callback(...args)
        .catch(err => {
            if (attempts > count) throw err
            attempts++
            return _retry(...args)
        });
}

Upvotes: 4

Related Questions