5

I created a separate file with all my queries using pg-promise module for Node. While for most of them I just use req, res after a query, for one I want to return a value back. It does not work. It returns undefined.

passportLogin: (email)=> {
        db.one(`SELECT userid 
                FROM user`)
            .then( result => {
                return result;
            })
            .catch( error => {
                return error;
            });
    }
ocram
  • 1,384
  • 6
  • 20
  • 36
  • You define a function without a return value, so what do you expect? add a `return` before `db.one()` and you should get the promise. – Sirko Jul 23 '16 at 20:07
  • Adding `return` before `db.one()` and getting rid of the other two `return`s gives back an empty object. – ocram Jul 23 '16 at 20:17
  • Your `then()` and `catch()` are pretty much useless here anyways, so get rid of them all together. – Sirko Jul 23 '16 at 20:25
  • well the query is much more complex in reality, I need to catch if it returns more than one row... the object returned is still empty even if it should not be. – ocram Jul 23 '16 at 20:26
  • so why did you get rid of the two other `return`s then? If you return a value from a promise callback, it will return a new promise, which is resolved with that very value. I guess you will need the result in the code, which calls `passportLogin()`. – Sirko Jul 23 '16 at 20:29

1 Answers1

2

That code has two problems at the same time:

  • invalid promise use, when inside .catch you do return result, that's not how promise rejects are handled, you must either provide the error handling, or re-throw / re-reject the error.
  • invalid use of pg-promise library. You use method one that's supposed to reject when anything other than 1 record is returned, as per the method's documentation, and at the same time you are saying I need to catch if it returns more than one row... , which is a logical contradiction.

The result of it is as follows: your query executes successfully, and returns more than one record, which in turn makes method one reject, and then you take the rejection reason and turn it into a resolved one by doing return result. In all, your code is broken all over the place.

First, with pg-promise you are supposed to use the right method, according to the number of records you are expecting back, see The Basics.

And then handle .then/.catch according to your business logic. I can't be more specific here, because you did not provide further details on this.

Community
  • 1
  • 1
vitaly-t
  • 24,279
  • 15
  • 116
  • 138