Skip to content

Instantly share code, notes, and snippets.

@randycasburn
Created November 30, 2020 03:52
Show Gist options
  • Select an option

  • Save randycasburn/32c899ce44a878249f8d5cd4045bd09b to your computer and use it in GitHub Desktop.

Select an option

Save randycasburn/32c899ce44a878249f8d5cd4045bd09b to your computer and use it in GitHub Desktop.
Use of an Async Generator function to retrieve data over time and update the display with a subset of records at a time
// DOM element to recieve dispatched event and data
const showResults = document.getElementById('showResults');
// CustomEvent listener
showResults.addEventListener('gotData', doDOM);
// Random _count_ to show (between 1-5)
const numberToShow = Math.ceil(Math.random() * (5 - 1) + 1);
// iterator Object (has .next() method)
const iterator = nextSet(numberToShow);
/**
* An Async Generator function to produce _count_ number of data elements
* @param count
* @returns {AsyncGenerator<FlatArray<[], 1>[], void, *>}
*/
async function* nextSet(count) {
let page = 1;
let data = [];
let current = [];
let previous = [];
let currentStart = 0;
while (true) {
// get paginated results from jsonplaceholder by page number and _count_ of records
data.push(await fetch(`https://jsonplaceholder.typicode.com/posts?_page=${page++}&_limit=${count}`).then(res => res.json()));
data = data.flat();
Object.assign(previous, current);
[current] = [data.slice(currentStart,currentStart + count)];
if(JSON.stringify(previous) !== JSON.stringify(current)) {
yield current;
}
currentStart = currentStart + count;
if (currentStart >= data.length) {
currentStart = 0;
}
}
}
let iterations = 0;
/**
* CustomEvent Handler - fired when new data is recieved
*
* DOM manipulations
* All side effects are contained within one function
* @parm Event - contains detail with data
*/
function doDOM(e){
// just blast out the data
let text = JSON.stringify(e.detail,null,4);
iterations++;
if(iterations > 3) {
clearInterval(interval);
text = 'All Done';
}
// Dead simple animations...
$(showResults).fadeOut(1000, ()=>{
showResults.innerText = text;
$(showResults).fadeIn(1000).delay(5000);
})
}
// Each call to iterator.next() generates a call for more data
// Once the data is retrieved, fire the custom event
let interval = setInterval(async ()=>{
await iterator.next().then(result=> {
let dataEvent = new CustomEvent('gotData', { detail: result.value});
showResults.dispatchEvent(dataEvent);
});
}, 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment