mysql2中的承诺
最近,我想学习Node.js来帮助我找到工作,所以我启动了一个Web抓取应用程序。
我从mysql包开始,但是在编写代码后我没有想到这是一个异步过程。
然后我发现带有promise的mysql2,但是我不确定是否了解如何正确使用它们,并且我做错了。
这是我的代码
const mysql = require('mysql2');
const pool = mysql.createPool({ ... });
var categorias = [];
var querySQL;
/*
Here goes web scraping stuff not needed in this question
*/
pool.getConnection(function(err, connection){
if(err) throw err;
querySQL = "SELECT 1 FROM Categories LIMIT 1";
connection.promise().query(querySQL).then(([rows,fields])=> {
if (rows!=undefined) {
console.log("The table already exist");
}else {
querySQL = "CREATE TABLE Categories (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20))";
connection.query(querySQL,function(err,rows,field){
if(err) throw err;
console.log("The table has been created");
console.log(rows);
});
}
})
.catch(console.log)
.then( ()=> {
querySQL = "SELECT x FROM y";
connection.promise().query(querySQL).then(([rows,fields])=> {
/*
More stuff
*/
})
.catch(console.log)
.then( ()=> console.log("Promise ended") );
});
});
问题是我是否在执行类似的良好的诺言,还是有另一种方法,因为此代码是在没有数据库的情况下创建数据库表,然后插入数据。每次网站更新其内容时,在第一次插入之后,我将创建一个临时表来检查是否存在新的类别,对象...等,这使我在此承诺中有了更多的承诺。
回答如下:我建议尝试使用async / await语法,它使内容更具可读性。
这应该按照您的意愿进行:
async function tableExists(pool, tableName) {
try {
const query = `SELECT 1 FROM ${tableName} LIMIT 1;`;
await pool.execute(query);
return true;
} catch (err) {
return false;
}
}
async function createdb() {
const mysql = require('mysql2/promise');
const config = {
host: 'host',
user: 'username',
password: 'password_goes_here',
database: 'some_database'
}
const pool = mysql.createPool(config);
let tableOk = await tableExists(pool, "categories");
if (tableOk) {
console.log("Table 'Categories' already exists.");
return;
}
console.log("Table 'Categories' does not exist, creating...");
try {
const createQuery = "CREATE TABLE Categories (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20));";
await pool.execute(createQuery);
console.log("Table created successfully.");
} catch (err) {
console.error("Table creation failed:", err);
}
pool.end();
}
createdb();