ocram ocram - 4 months ago 25
Node.js Question

Return in pg-promise

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;
});
}

Answer

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.

Comments