title: Javascript Generators: Understanding them
body: <p>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.</p>
  
  <p>From what I understand, the <code>yield</code> keyword enables a currently executing block of code to <em>wait for a value</em> instead of throwing remaining code to be executed inside a callback. So, as most tutorials have pointed out, you can use this:</p>
  
  <pre><code>(function *() {
       // Wait until users have be got and put into value of `results`
       var results = yield db.get("users");
       // And continue
       view.display(results);
  })();
  </code></pre>
  
  <p>Instead of:</p>
  
  <pre><code>db.get("user", function(results) {
      view.display(results);
  });
  </code></pre>
  
  <p>Right, that's all well and good until I try to write my own generators. I've run into several hitches:</p>
  
  <ul>
  <li>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 <code>.next</code> somewhere, right?</li>
  <li>The entire API will have to be rewritten right down to the I/O calls to support generators, correct?</li>
  <li>From what I gather, <code>yield</code> seems to stand for <em>wait for the value</em> most general use cases whereas in the implementation part (read: return value to/inside <code>db.get</code>) <code>yield</code> seems to stand for <em>send this value back to currently waiting block to resume execution</em>.</li>
  </ul>
  
  <p>Take for example:</p>
  
  <pre><code>function *fn() {
      yield 1;
      yield "a";
  }
  
  var gen = fn();
  gen.next(); // 1
  gen.next(); // "a";
  </code></pre>
  
  <p><code>yield</code> 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 <code>db.get</code> and the resumes execution instead of "returning" or sending back a value. If the <code>db.get</code> case is true, is this not inherently synchronous? I mean, isn't it exactly the same as:</p>
  
  <pre><code>(function() {
       //Wait for the results
      var results = fs.readFileSync("users.txt");
      // Use results
      view.display(results);
  })();
  </code></pre>
  
  <p>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.</p>