异步mysql调用导致foreignkey错误|Node.js



我想用node.js创建一个数据库和一些表。问题是,这些表是同时创建的,有时(!(有些表没有创建,因为它们在创建引用表时不存在。是的,通常我会一个接一个地执行sql语句,所以如果我在mysql工作台中执行它,就不会出错。但在节点中,由于异步事件循环(如果我理解正确的话(,它将同时执行。

这是我的一些代码:

const pool = require("./database2"); // using the pool connection of mysql2
const executeOne = (sql) => {
pool.execute(sql, (err, result) => {
if (err) console.log(err);
})
}

client.on("guildCreate", (guild) => {
guildname = guild.name.replace(" ", "_");
const createTables = new Promise((resolve, reject) => {
executeOne(`CREATE DATABASE IF NOT EXISTS ${guildname}`);
//tried to set the checks off but doesn't work either
executeOne(`SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS;`); 
executeOne(`SET FOREIGN_KEY_CHECKS=0;`);
resolve()
})
createTables.then(() => {
executeOne("1st stmt"); //no foreign keys
})
.then(() => {
executeOne("2nd stmt"); //no fks
})
.then(() => {
executeOne("3rd stmt"); //1 fk referencing 1st stmt
})

.then(() => {
executeOne("4th stmt"); //no fks
})
.then(() => {
executeOne("5th stmt"); //2fks, one ref. 2nd stmt, one ref. 3rd stmt
})

.then(() => {
executeOne("6th stmt"); //2fks, one ref. 3rd stmt, one ref. 4th stmt
})
.catch((err) => {
console.log(err)
});
})

所以我基本上不明白如何一个接一个地执行这些语句,或者它们是其他方法吗?

谢谢你的帮助!

我解决了它。

我在.then()子句中添加了setTimeout()函数,并将延迟每子句设置为高100ms。这不是一个好方法,但它是有效的。

最新更新