I read about debounce this morning and ended up needing something similar to the concept in real life this evening to build a poll that checks whether a link I receive from an async call is ready to be used in a href element.
But what I'm asking for are
- highlights of the risk to my implementation,
- to learn if there are standard polling patterns for this use case, and
- how to refactor my implementation into any of these standard patterns.
After numerous iterations here's the code that worked
const handler = async () => {
document.querySelector('#trello-board-link').style.display = 'none';
document.querySelector('#trello-board-link-loader').style.display = 'block';
let link = await getLink();
let intervalId;
/**
* I initially used a while loop which blocked,
* and then refactored to use setInterval. I can't
* think of anything wrong with this as it is now, but is this risky or wrong in
* an actual production environment?
**/
if (link === undefined) {
intervalId = setInterval(async () => {
link = await getLink();
if (link) {
document.querySelector('#trello-board-link').href = link;
document.querySelector('#trello-board-link').style.display = 'block';
document.querySelector('#trello-board-link-loader').style.display = 'none';
clearInterval(intervalId);
}
}, 500);
} else {
document.querySelector('#trello-board-link').href = link;
document.querySelector('#trello-board-link').style.display = 'block';
document.querySelector('#trello-board-link-loader').style.display = 'none';
}
};
/**
* This is only here in case the href elements haven't loaded, but please what's a
* standard way to check if an element exists before accessing it? Right now I'm only
* checking if the Document has loaded, but not sure if this guarantees all elements
* have loaded.
**/
document.addEventListener('DOMContentLoaded', handler);
getLink is simply an async function that returns the resolved value of a promise
const getLink = async () => {
const res = await fetch(`some url`);
const result = await res.json();
link = result && result.member && result.member.metaData && result.member.metaData.trelloBoardUrl;
return link;
};