返回pg-promise [英] Return in pg-promise
问题描述
我使用pg-promise
模块为Node创建了一个包含所有查询的单独文件.虽然对于大多数查询,我只在查询后使用req, res
,但对于一个查询,我想返回一个值.这没用.返回undefined
.
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;
});
}
推荐答案
该代码同时存在两个问题:
That code has two problems at the same time:
- 无效的诺言使用,当在
.catch
中执行return result
时,这不是处理诺言拒绝的方式,您必须提供错误处理或重新抛出/重新拒绝错误. - pg-promise 库的无效使用.您使用方法一个,该方法应该在除根据该方法的文档,返回1条记录, ,并且同时您说的是
I need to catch if it returns more than one row...
,这是一个逻辑矛盾.
- invalid promise use, when inside
.catch
you doreturn 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.
首先,对于 pg-promise ,您应该使用正确的方法,根据您希望返回的记录数,请参阅基础知识.
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.
然后根据您的业务逻辑处理.then/.catch
.我在这里没有具体说明,因为您没有提供进一步的细节.
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.
这篇关于返回pg-promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!