Catching rejected fetch Promise
by gavinfoley
JavaScript
async function start() {
const delay = ms => new Promise(res => setTimeout(res, ms));
const waitPeriodInSeconds = 5;
let keepPollingForVideo = true;
while (keepPollingForVideo) {
try {
console.log("Polling....");
var res = await fetch('https://assets.educahq.com/image/view/6bea99d0-3e72-455d-affa-9e5b74b5b8cf/31772a3e-688e-497c-b66a-5708efdf2d8f/31772a3e-688e-497c-b66a-5708efdf2d8f_b95917c.mp4', {
method: 'HEAD'
});
if (res.redirected) {
console.log(`Redirected. Video is not ready. Waiting ${waitPeriodInSeconds} seconds.`);
await delay(waitPeriodInSeconds * 1000);
continue;
}
console.log("Video is ready.");
keepPolling = false;
} catch (e) {
console.log(`Error. Video is not ready. Waiting ${waitPeriodInSeconds} seconds.`);
await delay(waitPeriodInSeconds * 1000);
}
}
}
start();