title: Recursion with Q promises
body: <p>I have a scenario where recursion occurs with promises, and I need some help on this.</p>
  
  <p>I have an array that contains a sequence of messages. Each message can be either: 1 primitive, like a string; or 2 compound, which is just a pointer to a DB area that contains a sequence of messages. For example, the array can be: <code>['hello', (compound), 'there']</code>, where (compound) can contain <code>['how', 'are', 'you']</code> when the compound message is fetched from DB. Therefore, the final 'expanded' array looks like: <code>['hello', 'how', 'are', 'you', 'there']</code>. To completely convert an array of messages into an array of primitive messages is called 'expand'.</p>
  
  <p>Note that a message in a compound message can be also a compound message, this is where recursion gets in. For instance, if (compound) in the above example is <code>['how', 'are', 'you', (lower level compound)]</code>, and (lower level compound) is <code>['Tom', 'Jerry']</code>, then (compound) will be expanded into <code>['how', 'are', 'you', 'Tom', 'Jerry']</code>, and the original array will be expanded into <code>['hello', 'how', 'are', 'you', 'Tom', 'Jerry', 'there']</code>.</p>
  
  <p>Here is what I think the code looks like, without promises:</p>
  
  <pre><code>function expandMessages(messages, outputMessages) {
      messages.forEach(function(message) {
          if (message.primitive) {
              outputMessages.push(message);
          }
          else {
              var fetchedMessages = fetchMessages(message);
              expandMessages(fetchedMessages, outputMessages);
          }
      });
  }
  </code></pre>
  
  <p>In the above code, <code>fetchMessages</code> fetches messages from DB for a compound message.</p>
  
  <p>How should I promisify the above code, so that after the outer promise returns: 1 outputMessages contains only primitive messages; and 2 correct message order is maintained, that is, any compound message's 'submessages' are inserted to where the compound messages were in the original array.</p>
  
  <p>Thanks!</p>