Jakob Nielsen
Jakob Nielsen

Reputation: 5198

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) {
    return new Promise(async (resolve, reject) => {
        try {
            const url = `example.org`;
            const json = await this._sendRequest(url);
            resolve(json);
        } catch (e) {
            if( retries > 0 ) {
                return this.examplefunction(retries - 1);
            }
            else {
                reject("Unable to communicate with Server. Please try again later!");
            }
        }
    });
}

the function is beeing called like this:

backend.examplefunction(3).then(
    (json) => {
        console.log(json);
    },
    (reason) => {
        console.log.(reason);
    }
)

This code is executed in a React context, so it is also running through a babel transpilitaion.

My problem is that when it will finally reject after x retries this results in a Uncaught Promise Error:

Uncaught (in promise) Unable to communicate with Server. Please try again later!!

enter image description here

Could anybody explain to me why this is happening?

Upvotes: 0

Views: 306

Answers (1)

Bergi
Bergi

Reputation: 665574

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.

Upvotes: 2

Related Questions