Postgres INSERT 导致 UnhandledPromiseRejectionWarning
Posted
技术标签:
【中文标题】Postgres INSERT 导致 UnhandledPromiseRejectionWarning【英文标题】:Postgres INSERT causing UnhandledPromiseRejectionWarning 【发布时间】:2021-10-22 12:43:20 【问题描述】:我正在运行以下代码
const Client = require('pg');
const credentials =
user: "username",
host: "localhost",
database: "data",
password: "password",
port: 5432,
;
async function appendDb(val1, val2, val3)
try
const client = new Client(credentials);
await client.connect();
var a = await client.query(`INSERT INTO table (col1, col2, col3) VALUES ($val1, $val2, $val3)`);
await client.end();
return;
catch(err)
console.log(err);
appendDb('test', 'test', 'test');
并得到以下错误
(node:17372) UnhandledPromiseRejectionWarning: Error: Connection terminated
at Connection.con.once (/usr/local/urr/node_modules/pg/lib/client.js:254:9)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:194:15)
at Socket.<anonymous> (/usr/local/urr/node_modules/pg/lib/connection.js:78:10)
at Socket.emit (events.js:189:13)
at TCP._handle.close (net.js:600:12)
(node:17372) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:17372) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
由于我使用的是 catch,不知道为什么会发生这种情况?以下脚本工作正常
async function clientDemo()
try
const client = new Client(credentials);
console.log(client);
await client.connect();
const now = await client.query("SELECT NOW()");
await client.end();
return now;
catch(e)
console.log(e);
(async () =>
const clientResult = await clientDemo();
console.log("Time with client: " + clientResult.rows[0]["now"]);
)();
所以我认为这与无法连接到 Postgres 或无效凭据或类似情况无关。
【问题讨论】:
不应该 ($val1, $val2, $val3`);是 ($val1, $val2, $val3)`); ) 在那里? 我的错,在复制我的代码时搞砸了。不能解决问题:( 【参考方案1】:尝试以这种方式查询数据库。
const Client = require('pg');
const credentials =
user: "username",
host: "localhost",
database: "data",
password: "password",
port: 5432,
;
async function appendDb(val1, val2, val3)
try
const client = new Client(credentials);
await client.connect();
var a = await client.query('INSERT INTO table (col1, col2, col3) VALUES ($1, $2, $3)', [val1, val2, val3]);
await client.end();
return;
catch(err)
console.log(err);
(async () =>
await appendDb('test', 'test', 'test');
)();
【讨论】:
试过了,排除了错误,但仍然没有添加到数据库中。添加了 console.log 语句,现在似乎根本没有进入函数。 对不起,我的错。我错过了函数调用中的等待。这里 appendDb 是一个异步函数,所以它会返回一个 Promise。所以,我们需要等到 promise 解决。我已经编辑了我的答案。请检查并让我知道它是否正常工作。 也试过了,导致SyntaxError: await is only valid in async function
我已经更新了我的答案。请检查并让我知道它现在是否正常工作。以上是关于Postgres INSERT 导致 UnhandledPromiseRejectionWarning的主要内容,如果未能解决你的问题,请参考以下文章
Postgres INSERT ON CONFLICT DO UPDATE 与 INSERT 或 UPDATE
Postgres UPSERT (INSERT 或 UPDATE) 仅当值不同时
使用TRANSACTION postgres进行双重INSERT