首页 > 解决方案 > 如何在 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日志吗?我不是。

标签: node.js

解决方案


推荐阅读