node.js - 如何在 Node 中使用 Promises 链接数据库查询?
问题描述
我正在尝试使用 mysql2 模块在 Node.js 中链接一系列数据库查询。
首先,我将转向 async/await,但在此之前我想了解此方法。在使用我所理解的语法糖之前,我试图更详细地理解承诺。
这是我的代码:
const pool = mysql.createPool({
host: 'localhost',
user: process.env.MYSQL_USERNAME,
password: process.env.MYSQL_PASSWORD,
database: 'phones'
});
console.log(pool);
pool.getConnection((connection) => {
console.log('entered connection');
connection.promise().query('select * from lists')
.then(([rows, fields]) => {
const lists = rows;
return connection.promise().query('select * from numbers')
}).then(([rows, fields]) => {
const numbers = rows;
return numbers;
}).then(() => {
console.log(lists);
console.log(numbers);
return lists;
}).catch((error) => {
throw error;
}).finally(() => {
connection.end();
});
});
console.log('end');
这是输出:
PromisePool {
...
}
end
程序只是在那里等待,直到我按下 Ctrl-C 才退出。我足够了解,知道有一个等待解决的承诺,但我不明白为什么。我不应该至少得到entered connection
日志吗?我不是。
解决方案
推荐阅读
- javascript - Vue mixin 渲染 HTML 并附加到 $ref
- c# - SnmpSharpNet.SnmpException:“请求已达到最大重试次数。”
- python - 我想使用 python 在 mysql 中创建一个表,我得到了这个错误,但是我有一个名为 sam 的数据库,我该怎么办
- ios - iOS 中的 WebBLE 支持
- c++ - 从 C++ 中的库的多重继承具有歧义
- android-studio - Android Studio 和 Intelij Idea 中不可用的设备
- c# - 如何解决“Package Google Authenticator 1.2.1 已使用 .NETFramework 恢复”,但我不想升级到最新版本(C#)
- c# - 带有 EF Core 5.0 的 ASP Core 3.1 API
- python - 在 Python 3.8 中没有附加类的 TypedDict 的键入键、值
- amazon-web-services - AWS 过滤和导出日志