Asyncronously mapping over a collection with a function that returns a promise
<p>I'm trying to learn how to use Bluebird promises and I am a bit lost. </p>

<p>I have two database tables: <code>topic</code> and <code>subject</code>. </p>

<p>The <code>topic</code> table has a <code>subject_id</code> column, which can then be used to query the <code>subject</code> table for the subject title. </p>

<p>I have an <code>orm</code> that queries asynchronously and returns a promise.</p>

<p>Ultimately I am trying to write a model method for topics that does the lookup for you, injecting the <code>subject_title</code> returned from the subsequent <code>subject</code> queries into the each element in the array of objects initially returned from the <code>topic</code> query. </p>

<p>I am trying to use <code>Promise.map</code>, but this is not working. The code below does not work. I never expected it to, but I think it captures the essence of what i am trying to accomplish. </p>

<pre><code>var promise = orm.select({
    db:     db, 
    table:  'topic',  
    where:  args.where,
    order:  args.order,
    limit:  args.limit,
    offset: args.offset,
    group:  args.group
}).map(function (topic) {
    var promise = orm.select({
        db: db,
        table: 'subject',
        qrm: 'one',
        where: {id: topic.subject_id}
    }).then(function (subject) {
        topic.subject_title = subject;
    });
    return promise;
});

return promise;
</code></pre>

<p>So, assuming that a vanilla <code>topic</code> object has the properties: </p>

<pre><code>[subject_id, title, description]
</code></pre>

<p>And a <code>subject</code> object has:</p>

<pre><code>[id, title]
</code></pre>

<p>I want the above function to return an array of objects with the following properties:</p>

<pre><code>[subject_id, subject_title, title, description] 
</code></pre>

<p>What is the cleanest way to accomplish this?</p>