1

I have a function, which contains code along the lines of...

db.query(query).then(results => {
    _.each(results, result => {
        db.query(anotherQuery).then(
            /* modify result based off anotherQuery results */
        });
    });
    resolve(results);
});

What is happening, of course, is that resolve(results)) is being hit whilst the second request to the DB is being run, which means that the promise is not resolved to add the additional data before being returned.

Is there a pattern I can use to avoid this? I am using Sequelize, which is backed by Bluebird for Promises. It's a pattern I've come across a few times, and I've already looked at using wait.for but it seems to be outdated and unsupporting of Promises.

  • What is `resolve`? You should `return` a promise from a `then` callback to chain it. – Bergi Oct 05 '16 at 09:33
  • @Bergi resolve is the resolve parameter of new Promise((resolve, reject) => ... –  Oct 05 '16 at 09:35
  • I feared so. Avoid the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi Oct 05 '16 at 09:38

1 Answers1

2

You can use Promise.all function provided by Bluebird itself:

return db.query(query).then(results => {
    const promises = results.map(result => {
        return db.query(anotherQuery).then(
            /* modify result based off anotherQuery results */
        });
    });

    return Promise.all(promises);
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
qzb
  • 8,163
  • 3
  • 21
  • 27