I'm pretty sure my understanding of generators is inherently broken. All online resources seem to conflict and it makes for an incredibly difficult and confusing learning experience.
From what I understand, the yield
keyword enables a currently executing block of code to wait for a value instead of throwing remaining code to be executed inside a callback. So, as most tutorials have pointed out, you can use this:
(function *() {
// Wait until users have be got and put into value of `results`
var results = yield db.get("users");
// And continue
view.display(results);
})();
Instead of:
db.get("user", function(results) {
view.display(results);
});
Right, that's all well and good until I try to write my own generators. I've run into several hitches:
- The first example code I above will not run because there is nothing to iterate over the generator, correct? Some higher being has to call the
.next
somewhere, right? - The entire API will have to be rewritten right down to the I/O calls to support generators, correct?
- From what I gather,
yield
seems to stand for wait for the value most general use cases whereas in the implementation part (read: return value to/insidedb.get
)yield
seems to stand for send this value back to currently waiting block to resume execution.
Take for example:
function *fn() {
yield 1;
yield "a";
}
var gen = fn();
gen.next(); // 1
gen.next(); // "a";
yield
in that context is sending values back down instead of waiting for the results. In the first example above, it waits for the results from the db.get
and the resumes execution instead of "returning" or sending back a value. If the db.get
case is true, is this not inherently synchronous? I mean, isn't it exactly the same as:
(function() {
//Wait for the results
var results = fs.readFileSync("users.txt");
// Use results
view.display(results);
})();
Unfortunately, if it's any way clear from this question (probably the only thing clear) is that I don't understand generators. Hopefully, I might get some insight here.