gpt4 book ai didi

javascript - 测试所有已终止的功能

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:27 24 4
gpt4 key购买 nike

我正在使用 ElectronJSNode.JS 开发两个数据库(SQL ServerMySQL)之间的同步器> 一切工作正常,但我想在所有表同步时执行 window.close() 方法来终止应用程序(这是在 for 中异步完成的) > 循环)。

// I removed error and bank connection treatments because they are working

// Read json file that contains all tables and its columns (keys)
fs.readFile(ABSPATH + 'tables.json', 'utf8', async (err,json) => {
// Parse the content of the file into a JSON object
let vetor = JSON.parse(json)
// Foreach table
for (let i = 0; i < vetor.length; i++) {
// Read the table from SQL Server and save it falues into MySQL
await read(vetor[i].table,vetor[i].keys)
}
// Instead of closing, I'm just displaying this message on screen (for debugging)
document.body.innerHTML += "<h2>All data where inserted</h2>"
})


但是正如你所看到的,它是在返回函数之前返回最终结果,也就是说,它们仍然是异步的:

Click here to see the image


我相信我的错误是在以下函数中保存数据时发生的,因为我使用 console.log() 对其进行了测试,但我仍然无法使其同步:

con.connect(async err => {
// Begin MySQL Transaction
await con.beginTransaction(async err => {
// Clear the table
await con.query(`TRUNCATE TABLE ${table}`, err => {})
// Loop to insert all inputs into table
for (let i = 0; i < values.length; i++){
// Create and execute the query to input values into table
await con.query(createInsert(table,keys,values[0]), err => {})
}
// When all data are inputed, end Transaction
await con.commit(err => {
// Write in window that everything gonna allright
document.body.innerHTML += "<p>All data where successfully saved into " + table + ".</p>"
})
})
// End MySQL Transaction
})

最佳答案

就像 georg 告诉我的那样,问题是我试图等待异步函数,但等待只适用于 Promises。
我找到了对他和this answer的问候的答案。我在 StackOverflow 上收到的葡萄牙语版本。
因此,我只是将连接放入 Promise 中,如下所示:

// Save datas into MySQL Database
function save(table, keys, values) {
return new Promise((res, rej) => {
// MSSQL returns a JSON object filled with informations that I don't want
// so I filter only what I want: the result of the query
values = values.recordset
// Start a new MySQL connection
let con = mysql.createConnection({
user: OUSER,
password: OPASS,
server: OHOST,
port: OPORT,
database: ODB
})
con.connect(err => {
if (err) {
alert(err)
window.close()
}
con.beginTransaction(err => {
// This function is just for DontRepeatYourself
rollBack(con, err, rej)

con.query(`TRUNCATE TABLE ${table}`, err => { rollBack(con, err, rej) })
con.query(createInsert(table,keys,values[0]), err => { rollBack(con, err, rej) })
con.commit(err => {
rollBack(con, err, rej)
document.body.innerHTML += `<p>All data where successfully registered into ${table}.</p>`
res()
})
})
})
})
}

关于javascript - 测试所有已终止的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57698895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com