【问题标题】:how to return query value in a variable ( customerData )#Nodejs nodejs postgres如何在变量(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)
})

如何从查询中返回结果?

【问题讨论】:

    标签: node.js node-mysql node-postgres


    【解决方案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()做了
    猜你喜欢
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    相关资源
    最近更新 更多