Catching rejected fetch Promise
HTML
<button onclick="stopper()">
Stop!
</button>
JavaScript
// this is just a placeholder. It will eventually be a function that evaluates.
let validContinue = true;
function shouldContinue() {
return validContinue;
}
function stopper() {
validContinue = false;
}
async function wonderPoll(someUrl) {
// just a delay mechanism
function wait(ms = 1000) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
// the actual individual poll
async function pollingFunction(url) {
const response = await fetch(url, {
cache: 'no-store'
});
if (response.ok) {
return response;
} else {
Promise.reject(response);
}
}
// allegedly keep polling until condition is met. But the rejected Promise is breaking out!
while (shouldContinue()) {
try {
await wait();
const value = await pollingFunction(someUrl);
result = { value, status: 'fulfilled' };
} catch (reason) {
result = {
reason,
status: 'rejected'
};
}
}
// when the fetch hits a rejected state, we never get here!
console.log('done with the while loop, returning last successful result')
if (result.reason) {
throw result.reason;
}
return result.value;
}
const sampleUrl = 'https://get.geojs.io/v1/ip/country.json?ip=8.8.8.8';
const sampleUrl2 = 'http://totallybroken_fo_sho';
// swap the URL to test
wonderPoll(sampleUrl2)
.then((result) => {
console.log('got a result', result)
})
.catch((err) => {
console.log('got an error', err)
});