我在AWS lambda上有一个代码可以查询AWS RDS MySQL DB。
每当需要插入数据库时,它将运行该类:
const mysql = require('mysql');
const config = require('../config.js');
const con = mysql.createConnection(config);
async function insert_score_db(user,message_id,date_created,sprint){
//con.connect(function(err) {
//if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO user_records (user_name,message_id, date_created,sprint) VALUES ('"+user+"', "+ message_id + ", '"+date_created+"',"+ sprint+");";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
//con.end();
//con.destroy();
//});
}
module.exports={
insert_score_db
};
我没有使用,**con.connect(function(err){**
因为任何query
调用都隐式地建立了连接,如文档所述。
我也评论过,**con.end()**
因为此函数是由嵌套的异步循环运行的,并且会导致以下入队Hanshake:
ERROR Uncaught Exception {"errorType":"Error","errorMessage":"Cannot enqueue Handshake after invoking quit.","code":"PROTOCOL_ENQUEUE_AFTER_QUIT","fatal":false,"stack":["Error: Cannot enqueue Handshake after invoking quit."," at Protocol._validateEnqueue
我摆脱了**con.end()**
,所有代码都可以正确运行,但是函数以:结尾Task timed out after 210.10 seconds
。我的猜测是,数据库连接永远不会关闭到lambda执行无法完成。
使用嵌套异步循环运行数据库查询的潜在解决方案是什么?
将con.end()
和con.destroy()
放在的回调函数中con.query()
。