I've been experimenting with ES6 generators in Node now for a little while, and there's still one issue that I don't understand.
In regular callback Node, getting a value from a database and doing something else in parallel would look something like this:
function executeBoth(){
db.find("value", function(results){
console.log(results);
});
doSomethingElse("else", function(data){
console.log(data);
});
}
This example is totally contrived, but notice that by calling executeBoth()
, db.find
and doSomethingElse
do not wait for each other to finish and Node can just execute both around the same time and the code is non-blocking.
Here is a generator example that would attempt to do the same thing:
function* executeBoth(){
var results = yield db.find("value");
console.log(results);
var data = yield doSomethingElse("else");
console.log(data);
}
I don't understand how the above code avoids the first function from blocking the second. From what I've read (sources below), it seems that the entire generator suspends when it reaches the yield
keyword. This makes sense for the lines of code that rely on the value returned from that specific yield
, but doesn't this also mean that db.find
would block doSomethingElse
from executing?
It seems like it can be solved by wrapping each yield
ed value and the following code that relies on them in their own separate generators, then calling those generators from a normal function. Yet if this the most efficient way to create non-blocking code, it would encourage the over-usage of many small generator functions with potentially repeating, specialized code. Am I correctly understanding the underlying mechanics of generators? If so, what is the workaround for this? Thanks in advance.