0

Is it bad practice to resolve a promise in the 'then' of another promise chain?

Example:

function getConnection() {
    return new Promise(function(resolve, reject) {
        connect(function(err, conn) {
            if (err) {
                reject(err);
                return;
            }
            resolve(conn);
        });
    });
}

function query(sql) {
    return new Promise(function(resolve, reject) {
        getConnection()
            .then(function(conn) {
                conn.query(sql, function (err, results){
                    resolve(results)
                });
            })
            .catch(function(err) {
                reject(err)
            })
    });
}

The idea is that the 'query' Promise would be frequently used in the app. So instead of typing out the promise chain steps of connecting then something else then querying. I have a quick Promise that I drop in when needed.

Keep in mind that this example is simpler so there would be a few more chain steps that are abstracted away.

So my question is am I falling into some Promise anti pattern? I looked around and I didn't see my exact example. Are there any performance issues? Are there scenarios where my error is swallowed or my Promise is never fulfilled? Or am I simply over thinking the problem and creating a convoluted solution?

Regards

Michael
  • 501
  • 5
  • 12
  • If `getConnection()` returns a promise, what is purpose of `new Promise(function(resolve, reject) {})` at `query()` ? – guest271314 Jun 04 '16 at 16:17
  • 1
    We can't answer the question unless you tell us more about `connect` and `query`. If they return promises, then yes; if not, then no. You might also look at utilities that bridge Node-style callback APIs to promises; you're basically reinventing those in your code. – T.J. Crowder Jun 04 '16 at 16:21
  • 1
    **Yes**, it's an antipattern. Good that you suspecting something fishy here yourself! Regarding `conn.query`, you currently are ignoring the `err`or in its callback, you probably should reject from there. You definitely should [promisify](http://stackoverflow.com/q/22519784/1048572) it alone - then use `getConnection().then(conn => queryPromise(conn, sql))` – Bergi Jun 04 '16 at 16:31
  • 1
    @charlietfl: It already *is* an antipattern because the promise-returning `getConnection()` is called from inside the `Promise` constructor. – Bergi Jun 04 '16 at 16:32

0 Answers0