【发布时间】:2019-08-10 15:55:42
【问题描述】:
我遇到了一个问题,即对我的数据库的异步调用返回未定义。
“findOne”函数从数据库中检索一行,但.then(... 函数在该行返回之前正在执行。
我尝试更改我在 DB 函数 findOne 中返回的内容,并在函数调用中添加“等待”。我也尝试过使用Promise.resolve(db.findOne({requestbody}).then(...,但也没有运气。
这里是db.findOne 方法
const findOne = async (req) => {
const { teamId, channelId, isClosed } = req;
return db.query('SELECT * FROM polls where team_id= $1 and channel_id =$2 and is_closed = $3 LIMIT 1',
[teamId, channelId, isClosed],
(error, results) => {
if (error) {
throw error;
}
console.log("\nDBRes: \n", results.rows[0])
return results.rows[0];
}
);
};
这里是我调用函数的地方
app.post('/', (req, res) => {
const slashCommand = req.body.command;
switch (slashCommand) {
//...
//... Some other code
//...
case 'results':
db.findOne({
teamId: requestBody.team_id,
channelId: requestBody.channel_id,
isClosed: false,
})
.then((row) => {
console.log(row);
const poll = pollFuncs.getPollfromResultRow(row);
const displayText = pollFuncs.getFormattedPollResults(poll);
res.status(200).send({
text: displayText,
});
});
break;
//... The rest of the function
这是我得到的日志。
注意*我目前正在 .then(...) 函数和 pollFuncs.getPollfromResultRow(row); 函数内记录“行”对象
Bot is listening on port 3000
undefined
undefined
(node:14000) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property `id` of 'undefined' or 'null'.
at Object.getPollfromResultRow (C:\Users\ztb0504\Documents\Projects\Node\werewolfmod\pollFunctions.js:97:125)
at db.findOne.then (C:\Users\ztb0504\Documents\Projects\Node\werewolfmod\index.js:59:56)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:14000) 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:14000) [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.
DBRes:
{ id: '22',
poll_title: 'This is a new Pollstgresql',
//The rest of the expected data....
}
如果能提供任何有关如何使其按预期返回数据的指导,我将不胜感激。 谢谢!
【问题讨论】:
-
一个不相关的注释:您将错误从数据库回调堆栈中抛出,而不是放入您的承诺中。你不应该那样做。
-
@SOFe jfriend00 的回答也解决了这个问题。感谢您指出这一点。
标签: javascript node.js asynchronous async-await