title: ES6 generator functions in angular
body: <p>recently I started using generators in my angular project. Here's how I do it so far:</p>
  
  <pre><code>function loadPosts(skip) {
      return $rootScope.spawn(function *() {
          try {
              let promise = yield User.findAll();
              $timeout(function () {
                  // handle the user list
              });
          } catch (err) {
              // handle err
          }
      });
  } 
  </code></pre>
  
  <p>From what I've read the next part won't be necessary in es7, but currently I have the <code>spawn</code> function in the run block of my app.</p>
  
  <pre><code>$rootScope.spawn = function (generatorFunc) {
      function continuer(verb, arg) {
          var result;
          try {
              result = generator[verb](arg);
          } catch (err) {
              return Promise.reject(err);
          }
          if (result.done) {
              return result.value;
          } else {
              return Promise.resolve(result.value).then(onFulfilled, onRejected);
          }
      }
      var generator = generatorFunc();
      var onFulfilled = continuer.bind(continuer, "next");
      var onRejected = continuer.bind(continuer, "throw");
      return onFulfilled();
  };
  </code></pre>
  
  <p>Everything works find the way I do it at the moment, the only thing I really don't like is that I have to call <code>$timeout()</code> after each promise. If I don't my <code>$scope</code> variables initialized inside the timeout won't be initialized. It seems to me that angular digest system needs to be triggered manually.</p>
  
  <p>Why is that and is there a way to make this cleaner?</p>