nodejs mysql异步
我正在尝试通过此端点从我的MySQL数据库返回我的用户列表。
问题在于它返回“未定义”。
你知道如何解决这个问题吗?
提前thx :)
app.get("/users", async (req, res) => {
users = await query_my_users_from_db()
// Got "users = undefined" here
console.log(users)
return JSON.stringify(users)
})
async function query_my_users_from_db() {
var users = await db.query("SELECT * FROM `users`", function (err, result) {
if (err) throw err
users = Object.values(JSON.parse(JSON.stringify(result)))
return users
})
}
I'm trying to return my users list from my Mysql database through this endpoint.
The problem is that it return "undefined".
Do you know how to solv this?
Thx in advance :)
app.get("/users", async (req, res) => {
users = await query_my_users_from_db()
// Got "users = undefined" here
console.log(users)
return JSON.stringify(users)
})
async function query_my_users_from_db() {
var users = await db.query("SELECT * FROM `users`", function (err, result) {
if (err) throw err
users = Object.values(JSON.parse(JSON.stringify(result)))
return users
})
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
db.query
是基于回调的,因此您应该将代码更改为:删除所有异步\等待,因为您不使用任何承诺!
然后定义您的回调
并使用它像这样:
另一个选项是为mySQL使用一些基于承诺的包装程序包,有很多或使用Node
util.promisify()
( https://www.geeksforgeeks.org/node-js-js-util-promisify-method/ )并完全删除回调。希望它有帮助
Since
db.query
is callback based, you should change your code into:remove all the async\await since you are not using any promises!
then define your callback
and use it like this:
Another option is to use some promise-based wrapper package for MySQL, there is plenty or use node
util.promisify()
(https://www.geeksforgeeks.org/node-js-util-promisify-method/) and then use async\await and remove the callback altogether.Hope that it helps
我使用了它,它像魅力一样工作。
I used this and it's working like a charm.