如何在变量(customerData)中返回查询值#Nodejs nodejs postgres

Posted

技术标签:

【中文标题】如何在变量(customerData)中返回查询值#Nodejs nodejs postgres【英文标题】:how to return query value in a variable ( customerData )#Nodejs nodejs postgres 【发布时间】:2021-12-14 12:49:10 【问题描述】:

带有查询的代码:

var customerData =  pool.query('SELECT * FROM customers WHERE 
licensenumber = $1 AND phone = $2 ORDER BY id ASC LIMIT 1 ',
[Licensenumber,phone], (error, result) => 
if (error) 
throw error
res.status(200).json(result.rows)
)

如何从查询中返回结果?

【问题讨论】:

【参考方案1】:

你的问题不是很清楚,而且你发布的代码部分非常有限,我猜你想做类似的事情:

try 
 const customerData = await pool.query('SELECT * FROM customers WHERE licensenumber = $1 AND phone = $2 ORDER BY id ASC LIMIT 1 ', [Licensenumber,phone]);
 res.status(200).json(customerData.rows);
 catch (e)  console.error(`An error occured: $e`); 

文档说 Promise 是受支持的,所以首先你 await 进行响应,然后将其发送给客户端。

编辑:一些提示:

总是首选constlet,由于范围问题,不应使用var 总是更喜欢使用承诺而不是回调来避免callback-hell

【讨论】:

如何将查询返回值存储在 Nodejs 中的变量中 .. 你刚刚对const res = await pool.query()做了

以上是关于如何在变量(customerData)中返回查询值#Nodejs nodejs postgres的主要内容,如果未能解决你的问题,请参考以下文章

如何用批处理语句获取reg命令的返回值?

如何将变量连接到 SQL 中的查询中?

服务器错误后如何在触发器上记录绑定变量

返回要在 sql 查询中使用的用户当前位置的 lat 和 long 值

Grafana 配置变量

我在 forEach 中更新的变量,返回到它们的原始值 [重复]