Search code examples
javascriptpromisexmlhttprequest

Promises stop looping when XMLHttpRequest Internet is off


I have some code which loops 2 methods.

Method 2 checks a URL using XMLHttpRequest.

The problem I'm having is that when there Internet is active it continues to loop but as soon as I turn the Internet off XMLHttpRequest will fail and stop looping.

Here is the code:

    one() {
        return new Promise(resolve=> {
            // Does something and returns either true or false
        })

    }

    two() {
        return new Promise(resolve => {
            const httpRequest = new XMLHttpRequest();
            httpRequest.open("GET", 'someurl', true);
            httpRequest.send();
            httpRequest.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    resolve(this);
                }
            };
        })
    }

    loop() {
        setTimeout(() => {
            this.one()
                .then(()=>this.two().then(response => {
                    if (response.status === 200) {
                        // Its True
                    } else {
                        // Its False
                    }
                }))
                .then(()=>this.loop())
        }, 5000);
    }

}

How can I make it so it continues looping no matter what?


Solution

  • Try to add onerror handler

           httpRequest.onerror = function() {
               resolve({ error: true });
           };
    

    Also you may want to throw and catch an error

    two() {
        return new Promise((resolve, reject) {
           // ...
           httpRequest.onerror = function() {
               reject();
           };
        });
    }
    
    loop() {
        setTimeout(() => {
            this.one()
                .then(()=>this.two()
                // ...
                .then(() => this.loop())
                .catch(() => this.loop())
        }, 5000);
    }
    

    The second approach allows you to interrupt the promise chain immediately, it could be helpful in case you have three, four etc methods.