Return in pg-promise

ぐ巨炮叔叔 提交于 2019-12-12 15:28:36

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/38545958/return-in-pg-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!