Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active July 12, 2018 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/8964e6eaaecb86bfc9a01a455ddb35c1 to your computer and use it in GitHub Desktop.
Save ccnokes/8964e6eaaecb86bfc9a01a455ddb35c1 to your computer and use it in GitHub Desktop.
Generator function for infinite loading things
// See demo here: https://jsfiddle.net/ccnokes/xfu3yzce/
/* fake request for remote data */
function request(offset = 0) {
return new Promise((res) => {
let data = new Array(5).fill(offset).map((n, i) => n + i);
setTimeout(() => res({ total: 20, data }), 1000);
});
}
// why a generator? It has an easy built-in api for controlling it and it's closure can hold the bookkeeping details
function* infiniteLoad() {
let offset = 0;
let total = Infinity; // set it to max until we know it from first response
while(offset < total) {
yield request(offset)
.then(res => {
total = res.total;
offset += res.data.length;
return res;
});
}
return { offset, total };
}
// test it out...
async function test() {
for await(let item of infiniteLoad()) {
console.log(item);
}
}
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment