首页 > 解决方案 > 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(.......);
            }   
        });
    }

感谢您的帮助。;-)

标签: mysqlnode.jsasynchronousaws-cli

解决方案


跟踪函数是否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);
  });
}


推荐阅读