此Lambda-AWS

时间:2018-12-03 11:50:13

标签: node.js amazon-web-services api aws-lambda

我具有以下通过API网关调用的Lambda函数:

var mysql = require('mysql');

var connection = mysql.createConnection({
    host: '[my_endpoint]',
    user: '[my_user]',
    password: '[my_password]',
    database: '[my_db]',
});

// console.log(connection);
exports.handler = (event, context, callback) => {
    connection.query('SELECT [field_name] FROM [table_name] WHERE [field_name] = \"' + event['queryStringParameters']['myParam'] + '\"', function (error, results, fields) {
        if (error) {
            connection.end();
            throw error;
        } else {
            // connected!
            console.log("Success! : " + event['queryStringParameters']['myparam'])
            console.log(results);

            var response = {
                "statusCode": 200,
                "headers": {
                    "my_header": "success"
                },
                "body": JSON.stringify(results),
                "isBase64Encoded": false

            };

            callback(error, response);
            connection.end(function (err) { callback(err, response);});
        }
    });
};

由于某种原因,我每第二次GET方法调用都会得到状态代码200和502(即,在一个调用中有200个状态代码,其中有一个数据,然后在下一个调用中有502状态代码,每隔一个调用就更改一次)

看着CloudWatch,我看到以下错误:

 Error: Cannot enqueue Query after invoking quit

对为什么发生这种情况有任何见解吗?我该如何解决?

1 个答案:

答案 0 :(得分:1)

AWS Lambda supports Node.js v.8.10, so you can write your code using async/await and Promises.

// You don't need callback here with nodejs v.8.10
exports.handler = async (event, context) => {
  context.callbackWaitsForEmptyEventLoop = false;

  var connection = mysql.createConnection({
       host: '[my_endpoint]',
       user: '[my_user]',
       password: '[my_password]',
       database: '[my_db]',
  });

  const queryRow = `SELECT ${field_name} FROM ${table_name} WHERE ${field_name} = "${event['queryStringParameters']['myParam']}"`;

  // We use only resolve for simplicity. In this particular case to remove try/catch. 
  // In your production code you should use resolve and reject to handle promise.
  const queryResult = await new Promise((resolve) => {
     connection.query(queryRow, (err, results, fields) => {
        if (err) return resolve(false);
        resolve(results);
      });
  });

  // We can close connection here, because no more actions with db required.
  connection.end();

  if (!queryResult) {
    return { statusCode: 404, body: JSON.stringify({ message: 'DB error' }) };
  }

  return {
    statusCode: 200,
    body: JSON.stringify(queryResult),
    headers: {
      my_header: 'success',
    },
  };

};

About context.callbackWaitsForEmptyEventLoop.