Last active
July 12, 2018 19:12
-
-
Save ccnokes/8964e6eaaecb86bfc9a01a455ddb35c1 to your computer and use it in GitHub Desktop.
Generator function for infinite loading things
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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