title: Making a synchronous loop from synchronous callbacks with node.js + Q deferred/promises module
body: <p>The popular JavaScript module <a href="http://documentup.com/kriskowal/q/" rel="nofollow">Q</a> implements the deferred / promise / futures concept. I think it's mainly used with node.js but it support browser use as well. I'm using it with node.js.</p>
  
  <p>To do sequential calls you chain one promise to the next using <code>then()</code> but in a loop it can be so counterintuitive than I'm finding it difficult to do the same as this pseudocode:</p>
  
  <pre><code>forever {
      l = getline();
  
      if (l === undefined) {
          break;
      } else {
          doStuff(l);
      }
  }
  </code></pre>
  
  <p>The Q documentation includes an example which seems pretty similar:</p>
  
  <pre><code>var funcs = [foo, bar, baz, qux];
  
  var result = Q.resolve(initialVal);
  funcs.forEach(function (f) {
      result = result.then(f);
  });
  return result;
  </code></pre>
  
  <p>But in trying many ways to adapt this example to my problem I'm having no success at all.</p>
  
  <p>Unlike in the example code I'm not iterating over an array but wish to loop until an end condition is met. Also I always call the same function. My function does not take the previous result as a parameter to the next call. Each call takes no arguments but the return value decides whether to continue the loop.</p>
  
  <p>These seemingly trivial differences are causing some kind of insurmountable mental block. Now I can see why many people have trouble understanding promises.</p>