I have a hard time understanding generators. But I think what I\'m trying to do should be possible.
I have an object Topic
that has access to Page
I do want to refactor
Topic
such that I can access it's pages through a generator, in stead of through a callback. Is that doable, without too much hassle?
No, not really. You are mixing two concepts here:
result
iteratorThere are ideas to merge the two concepts once the second has gotten its own keywords (async
/await
), but that's not applicable yet (the async iteration proposal is in stage 3). You are stuck with a "nested" structure, that array-like iterator inside an asynchronous callback.
So you can use a generator for either, but not one for both. And it's questionable whether that's worth it. Notice that neither will make your code synchronous, you will always have to use async callbacks in some regard.
Call back with a generator instance, not an array:
function Topic( id ) {
var repository = new PageRepository();
this.id = id;
this.getAllPages = function( callback ) {
repository.getAllPagesByTopicId( this.id, function( result ) {
callback( function* () {
while( result.hasNext() ) {
yield result.next();
}
}() );
} );
}
}
var topic = new Topic( 1 );
topic.getAllPages( function( pageiterator ) {
for( let page of pageiterator ) {
console.log( page ); // received next Page
}
} );
Don't call back a function, but resume a generator (like in the simplest async example):
function Topic( id ) {
var repository = new PageRepository();
this.id = id;
this.getAllPages = function( it ) {
repository.getAllPagesByTopicId( this.id, function( result ) {
for (var pages = [], result.hasNext(); ) pages.push( result.next() );
it.next( pages );
} );
}
}
var it = (function *() {
var topic = new Topic( 1 );
var pages = yield topic.getAllPages( it );
console.log( pages ) // received Page instances
}());
it.next();
Yes, you can use both approaches at once (passing the generator-created iterator into the next
method of the async generator), but that's probably quite confusing. And they'll stay separate generators.