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
s. Originally Topic
was implemented such that Page
s would be retrieved through a callback.
var Topic = function( id ) {
var repository = new PageRepository();
this.id = id;
this.getAllPages = function( callback ) {
repository.getAllPagesByTopicId( this.id, function( result ) {
var pages = [];
while( result.hasNext() ) {
pages.push( result.next() );
}
callback( pages );
} );
}
}
var topic = new Topic( 1 );
topic.getAllPages( function( pages ) {
console.log( pages ) // received Page instances
} );
Now, let's assume I cannot refactor PageRepository
's callback mechanism, but 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 hastle?
I know I can iterate generator values with a for...of
statement, like:
var topic = new Topic( 1 );
for( let page of topic.pages() ) { // create the generator
console.log( page ); // received next Page
}
... so I came up of with something like the following:
var Topic = function( id ) {
...
this.pages = function*() { // refactored getAllPages () to a generator function pages()
repository.getAllPagesByTopicId( this.id, function( result ) {
while( result.hasNext() ) {
yield result.next(); // yield the next Page
}
} );
}
}
However, this doesn't work, probably because yield
is called from within the callback.
Then, based my (poor) understandings of this article (from "To use a generator ..." onward), I thought this might work:
var Topic = function( id ) {
...
this.pages = function*() {
let gen = function*() {}(); // create an inner generator
// not actually sure why the following wrapper function is needed
// but something similar is used in mentioned article
yield function() {
repository.getAllPagesByTopicId( this.id, function( result ) {
while( result.hasNext() ) {
gen.next( result.next() ); // call next() on inner generator
}
} );
}(); // immediately create this mysterious wrapper function
}
}
But this doesn't work either, unfortunately.
So, is what I'm trying to achieve doable, without too much hassle; meaning: no modules (like co, suspend, etc...) and/or convoluted thunk generators and what have you?
See Question&Answers more detail:
os