循环内的 AWS Lambda nodejs mysql 查询不起作用

PPShein
module.exports.handler = async (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  let index = 0;
    var client = mysql.createConnection({
      host: process.env.rds_host,
      user: process.env.rds_username,
      password: process.env.rds_password,
      port: process.env.rds_port
    });
    client.connect((err) => {
      if (err) throw err;
      console.log("Connected!");
    });
  let array = [];
  let queries = ["query1", "query2", "query3", "query4"];
  queries.map(q => {
    array.push(getQueryResult(client, q));
  });
  Promise.all(array).then(result => {
    console.log(result);
  });
  callback(null, {});
};

const getQueryResult = async (client, query) => {
  return new Promise((resolve, reject) => {
    client.query(query, function (err, result) {
      if (err) {
        reject(err);
      }
      resolve(result);
    });
  });
};

以上是我从 mysql 执行多个查询的 lambda 脚本。问题是我没有从上述脚本中得到任何结果和错误消息。请帮助我的脚本中缺少某些内容?

破烂不堪

上面的代码有两个或三个(潜在)问题:

  1. 您的 if 语句没有得到评估,因为typeof客户端谓词不返回 true。

  2. 您的mysql端口与您端口冲突localhost(假设)

像这样改变你的 if 块:

 // check if `dotenv` has been called if you use it
 require('dotenv').config();
 
 // access the state property on mysql object
 // if you have closed your connection previously
 // this will get evaluated by the parser
 if (mysql.state === "disconnected") {  
 
      var client = mysql.createConnection({
          host: process.env.rds_host,
          user: process.env.rds_username,
          password: process.env.rds_password,
          port: process.env.rds_port        // is your port the same as your localhost?
          // include your database name here
        });
     
      // I suggest you to await your client connection
      // since mysql executes sequentially, not asynchronously
      client.connect(function(err) => {
          if (err) {
            console.error('error connecting: ' + err.stack);
            return;
          }
          console.log("Connected!");
        });
 }

如果错误仍然存​​在,则意味着您的环境变量设置不正确,因此应检查您的数据库配置(请参阅内嵌注释)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章