I have a function that fetches rows of a database asynchronously, and calls a callback function for each row. I am trying to write a wrapper which is a generator function which yields each time a row is returned, but I am not seeing how to properly yield.
The original code looks something like this:
db.each(query, (err, row) => {
// do something here with row
}, () => {
// called after the last row is returned
})
I'm familiar with how a generator works, but the yield seems to belong in the generator function itself, not in an anonymous function. So I think something like this wouldn't work:
function* dbEach(db, query) {
db.each(query, (err, row) => {
yield row
})
}
When I actually try this I get an error "Unexpected identifier".
I looked a bit further and it appears that ES2018 now has asynchronous iterators which are supposed to make this possible. However, I'm having trouble wrapping my head around how exactly I can use async iterators in the case where I already have a callback which is getting called multiple times.