NodeJs:Promise 始终返回未定义
所以我有以下承诺应该进入我的 sqlite 数据库并告诉我是否有匹配。即使变量是正确的,它也总是返回未定义的。
var checkLoanable = function(bookID){
return new Promise((resolve, reject)=>{
db.run('SELECT * FROM book WHERE id=?',[bookID],(err,row)=>{
if (err) {
console.log("error")
reject();
}
if(row){
if(row.loanable==0){
console.log("not loanable")
reject();
}
console.log("success")
resolve(row);
}else{
console.log("undefined")
reject();
}
console.log("End of promise")
});
})
}
这是函数的调用,
await checkLoanable(bookID)
.then(()=>{console.log("success")})
.catch(()=>{
res.status(422)
.setHeader('content-type', 'application/json')
.send({ message: "Failed to add loan: book is not loanable!"});
});
console.log("after promise");
await 位于异步函数内部,经过我所做的测试,它确实等待承诺结束,然后继续执行代码。我不明白为什么它总是未定义。 预先感谢您的帮助。
So I have the following promise that is supposed to go inside my sqlite database and tell me if there is a match. Even if the variables are correct it always returns undefined.
var checkLoanable = function(bookID){
return new Promise((resolve, reject)=>{
db.run('SELECT * FROM book WHERE id=?',[bookID],(err,row)=>{
if (err) {
console.log("error")
reject();
}
if(row){
if(row.loanable==0){
console.log("not loanable")
reject();
}
console.log("success")
resolve(row);
}else{
console.log("undefined")
reject();
}
console.log("End of promise")
});
})
}
This is the call of the function
await checkLoanable(bookID)
.then(()=>{console.log("success")})
.catch(()=>{
res.status(422)
.setHeader('content-type', 'application/json')
.send({ message: "Failed to add loan: book is not loanable!"});
});
console.log("after promise");
The await is inside an async function and after tests I did it does wait for the promise to end and then continues the code. I can't figure out why its always undefined though.
Thank you in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
run()
用于插入和更新行。要获取单行,请使用 db.get()。
至少如果您使用 npm/sqlite 包。
run()
is used for inserting and updating rows.For getting a single row use
db.get()
.At least if you are using the npm/sqlite package.
不要混合使用 async/await 和 Promise 链之一。
使用 try...catch 或
Promise..then..catch
例如,如果您使用类似这样的
结果,则不会
同时获取值。
Do not mix
async/await
andPromise
chain use one of them.Either with try...catch or
Promise..then..catch
For the example if you use something like this
Result would be
Not both get values at the same time.