【问题标题】:Node.js await postgresql errorNode.js 等待 postgresql 错误
【发布时间】:2018-01-30 19:34:48
【问题描述】:

我使用 express 和 PostgreSql。

我的项目文件夹:

-Model
    -Visitor.js
-app.js

我已经将 postgresql 与 pg 连接起来,并且我已经使用查询进行了测试。它运行良好。但是,有一个关于 Visitor.js 文件的查询。

var visitor = function() {
    this.add = function() {
        var ret = false;
        db.query({text: 'INSERT INTO visitor(visitorid, data, status) VALUES($1, $2, $3)', values:[id, JSON.stringify(data), "1"]}, function (err, response) {
            if(!err) {
                ret = true;
            }
        });
        return ret;
    }
}

此查询总是在我的表中插入一行,但返回 false。此函数应等待查询结束。我该怎么做?

【问题讨论】:

    标签: javascript node.js postgresql async-await node-postgres


    【解决方案1】:

    你应该等待一个承诺

    this.add = function() {
        return new Promise((resolve, reject) => {
            db.query({text: 'INSERT INTO visitor(visitorid, data, status) VALUES($1, $2, $3)', values:[id, JSON.stringify(data), "1"]}, function (err, response) {
                if(!err)
                    resolve(response)
                else
                    reject(err)
            });
        })        
    }
    

    然后你可以在visitor.add函数上等待

    编辑 如果您使用pg 库:如Getting Started 所示,您可以直接在client.query 函数上等待,因为它在您不提供回调时返回一个Promise

    const { Client } = require('pg')
    const client = new Client()
    
    await client.connect()
    
    const res = await client.query('SELECT $1::text as message', ['Hello world!'])
    console.log(res.rows[0].message) // Hello world!
    await client.end()
    

    【讨论】:

    • 我已经尝试等待,再次等待 client.connect();然后我正在检索一个错误: SyntaxError: Unexpected identifier
    • 您只能在异步函数中等待。在 google 上搜索,每个 async/await 教程都说明了这一点
    猜你喜欢
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多