mysql - nodejs mysql如何在循环将数据输入数据库后关闭连接
问题描述
我有一个相当简单的程序,它使用 aws-cli 和 nodejs 从 aws 收集数据,然后将其输入 MySQL。公平地说,它确实有效,唯一的事情是我希望这个程序被安排不时运行,但我不能,因为它不会退出:当所有数据都输入后,我不会结束连接。我试图弄清楚如何使用 promises 和 async/await 来做到这一点(关闭/结束与 MySQL 的连接),但没有成功。肯定是我做的不对(到目前为止,我很难理解 Promise 和异步编程的概念),但我确实尝试了好几天。
[...]
function insertInstanceDetails(date, zone, instance_id, name){
let insert_details = "INSERT INTO instances (date, zone, instance_type, name) VALUES(" + db.escape(date) + "," + db.escape(zone) + "," + db.escape(instance_id) + "," + db.escape(name) + ")";
db.query(insert_details, function(err, result){
if(err) throw err;
});
return;
}
for(instance-id of instance-ids){
aws.command('ec2 describe-instaces .....').then(function (data) {
var result = JSON.parse(data.raw);
for (var key in result.xyz) {
insertInstanceDetails(.......);
}
});
}
感谢您的帮助。;-)
解决方案
跟踪函数是否insertInstanceDetails
执行完毕的一种方法是将其转换为 Promise。
function insertInstanceDetails(date, zone, instance_id, name) {
return new Promise((resolve, reject) => {
let insert_details = "INSERT INTO instances (date, zone, instance_type, name) VALUES(" + db.escape(date) + "," + db.escape(zone) + "," + db.escape(instance_id) + "," + db.escape(name) + ")";
db.query(insert_details, function(err, result) {
if (err) return reject(err);
});
return resolve(result);
});
}
而对于for..of
循环,它将充当promise handler,一旦它知道所有的SQL作业都完成了,它会尽快关闭SQL连接
for (instance - id of instance - ids) {
aws.command('ec2 describe-instaces .....').then(function(data) {
var result = JSON.parse(data.raw);
const insertInserteDetailsJobs = [];
for (var key in result.xyz) {
insertInstanceDetailsJobs.push(insertInstanceDetails(.......));
}
// Handle, and watch over all those micro-promise
return Promise.all(insertInstanceDetailsJobs);
})
.then(sqlResults => {
// Now we know all the insert details has beeing successfully inseted into your DB
// We can now close the SQL connection safely
...
myDB.close();
})
.catch(err => {
// Something fail
console.error(err);
});
}
推荐阅读
- pandas - 如何用键保存分组结果索引?
- reactjs - 如何在 Parent 的孩子中使用 ref 访问 Child - React@latest
- javascript - 如何配置 ESLint 以捕获未声明的局部变量
- c++ - 为什么别名声明不是有效的初始化语句(/simple-declaration)?
- visual-studio-code - VS 代码中的扩展警告
- javascript - 添加新属性的对象循环数组不起作用
- oracle - RMAN 备份因文件写入错误而失败
- azure - Azure Data Lake Gen2 与存储帐户
- python - 如何从 GridSearchCV 输出可视化 XGBoost 树?
- java - 我在保存一个称为分区等于子集和的动态编程问题时遇到问题