mysql2 中的承诺
Promises in mysql2
最近我想学习 Node.js 以帮助我找到工作,所以我开始使用网络抓取应用程序。
我从 mysql 包开始,但在编写代码后我没有想到这是一个异步过程。
然后我发现 mysql2 有 promises 但我不确定我是否理解如何正确使用它们并且我正在做一个错误的做法。
这是我的代码
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") );
});
});
问题是我是否正在做这样好的链接承诺,或者有另一种方法,因为这段代码是创建数据库的 tables,如果没有的话,然后插入数据.每次网站更新其内容时第一次插入后,我将创建一个临时的 table 来检查是否有新的类别、对象...等等,这样我就可以在这个承诺中得到更多的承诺。
我建议尝试使用 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();
你的 promises can you chained 更好一点,we have a problem with promises 这篇文章帮助我更好地理解了 promises。
你应该避免嵌套承诺,你的案例你可以 return 你的承诺的价值链 them.Great 关于 Promise chaining
的例子
我会像这样展开你的承诺结构。
pool.getConnection(function(err, connection){
if(err) throw err;
var querySQL = "SELECT 1 FROM Categories LIMIT 1";
return connection.promise().query(querySQL)
.then((results)=> {
if (results.rows!=undefined) {
console.error("The table already exist");
throw "The table already exist";
}
else {
let querySQL = "CREATE TABLE Categories (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20))";
return connection.query(querySQL);
}
})
.then((err, rows,) => {
if(err) throw err;
console.log("The table has been created");
console.log(rows);
return rows;
})
.catch(console.log)
.finally(()=> {
var querySQL = "SELECT x FROM y";
return connection.promise().query(querySQL)
})
.then((results, error) => {
/*
More stuff
*/
return nextPromise;
// .then( ()=> console.log("Promise ended") );
})
.then(() =>{
console.log("Promise ended")
})
});
最近我想学习 Node.js 以帮助我找到工作,所以我开始使用网络抓取应用程序。
我从 mysql 包开始,但在编写代码后我没有想到这是一个异步过程。
然后我发现 mysql2 有 promises 但我不确定我是否理解如何正确使用它们并且我正在做一个错误的做法。
这是我的代码
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") );
});
});
问题是我是否正在做这样好的链接承诺,或者有另一种方法,因为这段代码是创建数据库的 tables,如果没有的话,然后插入数据.每次网站更新其内容时第一次插入后,我将创建一个临时的 table 来检查是否有新的类别、对象...等等,这样我就可以在这个承诺中得到更多的承诺。
我建议尝试使用 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();
你的 promises can you chained 更好一点,we have a problem with promises 这篇文章帮助我更好地理解了 promises。
你应该避免嵌套承诺,你的案例你可以 return 你的承诺的价值链 them.Great 关于 Promise chaining
的例子我会像这样展开你的承诺结构。
pool.getConnection(function(err, connection){
if(err) throw err;
var querySQL = "SELECT 1 FROM Categories LIMIT 1";
return connection.promise().query(querySQL)
.then((results)=> {
if (results.rows!=undefined) {
console.error("The table already exist");
throw "The table already exist";
}
else {
let querySQL = "CREATE TABLE Categories (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20))";
return connection.query(querySQL);
}
})
.then((err, rows,) => {
if(err) throw err;
console.log("The table has been created");
console.log(rows);
return rows;
})
.catch(console.log)
.finally(()=> {
var querySQL = "SELECT x FROM y";
return connection.promise().query(querySQL)
})
.then((results, error) => {
/*
More stuff
*/
return nextPromise;
// .then( ()=> console.log("Promise ended") );
})
.then(() =>{
console.log("Promise ended")
})
});