I am fetching data from backend service, 20 results at a time. I would like to hide this implementation detail and create a generator that would keep returning records for as long as I need them (while they are available).
Naive implementation:
function* getEndlessRecords(fetchingFunction) {
const batchSize = 20;
// endless loop:
for (let offset = 0; true; offset += batchSize) {
fetchingFunction(offset, batchSize)
.then(records => {
for (let i=0; i < records.length; i++) {
yield records[i]; // THIS DOESN'T WORK!!!
}
})
}
}
(there might be typos - this is simplified code)
I understand why this doesn't work (yield works on innermost function), however I can't seem to find a nice way to create a generator around the async functions.
Is it possible for generator to consume output from async functions?
next). But you can use async generators