gpt4 book ai didi

javascript - Express Postgres 未处理的 Promise 拒绝警告

转载 作者:行者123 更新时间:2023-12-03 00:45:56 24 4
gpt4 key购买 nike

我正在使用express和postgres学习Node JS,当我制作CRUD应用程序时,当我执行INSERT INTO语句时,我遇到了这样的错误。

(node:4998) UnhandledPromiseRejectionWarning: TypeError: Invalid Query Result Mask specified.
at Database.$query (/home/aabishkar/Documents/meanstack/node_modules/pg-promise/lib/query.js:121:25)
at Database.<anonymous> (/home/aabishkar/Documents/meanstack/node_modules/pg-promise/lib/query.js:259:23)
at config.$npm.connect.pool.then.db (/home/aabishkar/Documents/meanstack/node_modules/pg-promise/lib/database.js:326:42)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7) (node:4998) 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: 3) (node:4998) [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.

我的代码如下所示:

exports.dynamicadd =  function(req, res) {
var name = req.body.name;
var dob = req.body.dob;
var gender = req.body.gender;
var values = [name, gender, dob];
console.log(values); //Up to here code is fine. It returns the value.
//from here the error comes
var sql = "INSERT INTO students (name, gender, dob) VALUES ?";
db.query(sql, [values], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
res.redirect('/');
}

数据库已连接。另外,作为引用,以下代码工作正常。当我尝试动态插入值时出现错误。

//this codes works finely
exports.addlist = function(req, res) {
qry = "INSERT INTO students (name, gender, dob) VALUES ('sdasda', 'male', '12-12-1999')";
db.query(qry, function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
res.redirect('/');
}

谢谢。

最佳答案

pg-promise返回一个 promise,它不接受回调。您错误地使用了该库。当values是第二个参数时,那么第三个参数不应该是回调,它应该是QueryResultMask

您应该使用它是:

db.query(...)
.then(r => console.log(r))
.catch(e => console.log(e))

看看这个 simple insert example

关于javascript - Express Postgres 未处理的 Promise 拒绝警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53250276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com