简体   繁体   English

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

[英]AWS Lambda nodejs mysql query inside loop is not working

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);
    });
  });
};

Above is my lambda scripts to execute multiple query from mysql.以上是我的 lambda 脚本,用于从 mysql 执行多个查询。 The problem is I didn't get any result and error message from above scripts.问题是我没有从上面的脚本中得到任何结果和错误消息。 Please help me something is missing inside my scripts?请帮助我的脚本中缺少某些内容?

There are two or three (potential) issues with your code above:上面的代码存在两个或三个(潜在)问题:

  1. Your if statement does not get evaluated because of the typeof client predicate does not return true.由于typeof客户端谓词未返回 true,因此您的 if 语句未得到评估。

  2. your mysql port conflicts with your localhost port (assumption)您的mysql端口与您的localhost端口冲突(假设)

Change your if block as such:像这样更改您的 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!");
        });
 }

if the error persists, it means that your enviroment variables are not set correctly so your db configuration should be reviewed (see inline comments).如果错误仍然存在,则意味着您的环境变量设置不正确,因此应检查您的数据库配置(请参阅内联注释)。

The issue is >> code is not waiting to finish Promise问题是 >> 代码没有等待完成 Promise

You can resolve by:您可以通过以下方式解决:

Add callback in then然后添加回调

Promise.all(array).then(result => {
    console.log(result);
    callback(null, {});
  });

OR或者

Use await使用等待

let result = await Promise.all(promiseArray);
console.log(result)
callback(null, {});

Note: Use try-catch to handle error in for await注意:使用 try-catch 处理等待中的错误

Also, don't use map to loop array instead use For loop .另外,不要使用map来循环数组,而是使用For loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM