Skip to content Skip to sidebar Skip to footer

Promise Error Propagation

I have this function which will if it fails retry, and if it fails x times it should finally reject the Promise. I have implemented this as follows: examplefunction(retries = -1) {

Solution 1:

Avoid the Promise constructor antipattern, and never pass an async function to it! You should write

async function example(retries = -1) { /*
^^^^^ */
    try {
        const url = `example.org`;
        const json = await this._sendRequest(url);
        return json;
//      ^^^^^^
    } catch (e) {
        if (retries > 0) {
            return this.examplefunction(retries - 1);
//          ^^^^^^ this works as expected now
        } else {
            throw new Error("Unable to communicate with Server. Please try again later!");
//          ^^^^^
        }
    }
}

You were never resolveing the promise in the retry case, and when the recursive call failed eventually then that promise was completely ignored.


Post a Comment for "Promise Error Propagation"