Polling with fetch()
by gavinfoley
JavaScript
async function pollForVideo() {
const delay = seconds => new Promise(res => setTimeout(res, seconds * 1000));
const waitPeriodInSeconds = 5;
let keepPollingForVideo = true;
while (keepPollingForVideo) {
try {
console.log("Polling....");
// Working URL
//const videoUrl = "https://assets.educahq.com/story/videoencoding.mp4";
// Broken URL e.g. emulating a video that hasnt been transcoded yet
const videoUrl = "https://assets.educahq.com/story/videoencoding.mp4";
const res = await fetch(videoUrl, {
method: 'HEAD' // HEAD are like GET requests except they don't include the response body
});
if (res.redirected) {
console.log(`Redirected. Video is not ready. Waiting ${waitPeriodInSeconds} seconds.`);
await delay(waitPeriodInSeconds);
continue;
}
console.log("Video is ready.");
keepPollingForVideo = false;
} catch (e) {
console.log(`Error. Video is not ready. Waiting ${waitPeriodInSeconds} seconds.`);
await delay(waitPeriodInSeconds);
}
}
}
pollForVideo();