我有以下代码:
pool.getConnection()
.then(conn => {
return conn.query("SELECT table_name FROM information_schema.tables WHERE TABLE_SCHEMA='SquadgoalsDB';")
.then((rows)=>{
for(let i=0; i< rows.length;i++){
tableNames.push(rows[i].table_name)
}
tableNames = []
if(tableNames.length == 0){
throw new Error("NO_TABLES_FOUND")
}
return conn.query("select DISTINCT(column_name) from information_schema.columns WHERE TABLE_SCHEMA='SquadgoalsDB'")
})
.then((rows)=>{
for(let i=0; i< rows.length;i++){
columnNames.push(rows[i].column_name)
}
if(columnNames.length == 0){
throw new Error("NO_COLUMNS_FOUND")
}
conn.end()
console.log("MariaDB connection works")
})
.catch((err) =>{
throw err;
conn.end()
})
}).catch(err =>{
console.log("not connected to mariadb due to error: " + err);
});
module.exports.tableNames = tableNames; //always empty
module.exports.columnNames = columnNames; // always empty
我想搜索数据库中的所有表和列名。在这之后,我有更多的服务器启动工作,我想导出上面显示的两个数组,但它们总是空的,因为我们不等待查询?我如何等待(可能使用async/await(上面的代码完成,然后继续进行导出和其他操作?
感谢您帮助
我相信你可以这样做:wait应该等待整个承诺链完成,它应该接收一个表示已解决或已拒绝承诺的对象。但请记住,导出也是一个async操作,因此它可能在函数完成之前发生。
使用ansync系统的最佳方法是使用回调。您需要导出一个回调分配方法来获取回调,并在异步执行时调用它。
module.exports = pool.getConnection()
.then( async (conn) => {
return await conn.query("SELECT table_name FROM information_schema.tables WHERE TABLE_SCHEMA='SquadgoalsDB';")
.then((rows)=>{
for(let i=0; i< rows.length;i++){
tableNames.push(rows[i].table_name)
}
tableNames = []
if(tableNames.length == 0){
throw new Error("NO_TABLES_FOUND")
}
return conn.query("select DISTINCT(column_name) from information_schema.columns WHERE TABLE_SCHEMA='SquadgoalsDB'")
})
.then((rows)=>{
for(let i=0; i< rows.length;i++){
columnNames.push(rows[i].column_name)
}
if(columnNames.length == 0){
throw new Error("NO_COLUMNS_FOUND")
}
conn.end()
console.log("MariaDB connection works")
})
.catch((err) =>{
throw err;
conn.end()
})
}).catch(err =>{
console.log("not connected to mariadb due to error: " + err);
});
在另一个文件中,你可以做:
(async function(){
let foo = await require("./codeabove");
console.log(foo);
})();