I have a function that makes a server call and returns a promise, like so:
function postToServer(url, body) {
let xhr = new XMLHttpRequest();
xhr.open(`POST`, url, true);
xhr.setRequestHeader(`Content-type`, `application/json`);
return new Promise((resolve, reject) => {
xhr.onload = () => {
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
resolve();
} else {
reject(xhr.status);
}
};
xhr.send(body);
});
}
This seems to work just fine for my case. However, the problem comes when I want to retry that call on failure. I have a different function that performs this process:
function postToServerAndRetryOnFail(url, body, failedAttempts = 0) {
return new Promise((resolve, reject) => {
postToServer(url, body).then(() => {
resolve();
}, statusCode => {
failedAttempts++;
if(failedAttempts <= maxAttempts) {
wait(intervalBetweenAttempts).then(() => {
postToServerAndRetryOnFail(url, body, failedAttempts);
});
} else {
reject(statusCode);
}
});
});
}
What I would expect to happen here is, when the request fails, it tries until it reaches the maximum number of attempts, at which point it returns a rejection. Note that the function does behave as expected for successful requests.
What is actually happening is that it fails, retries, fails, ... (as expected) until it reaches the maximum number of tries. Then, instead of rejecting, I just get uncaught exception: 404
with no line number or stack trace. What's going on here? Why isn't it just rejecting as normal?