abdulelah
abdulelah

Reputation: 27

Lambda always returns null

Lambda function always returns null, and I think the function terminate before finishing all the tasks, because I noticed in the console logs sometimes I didn't get any data from the database or even the connection id, and sometimes I get it twice as you see below

START RequestId: e7a51db9-c36e-463b-ba82-2155c3829ee8 Version: $LATEST
2020-07-16T20:56:21.915Z    e7a51db9-c36e-463b-ba82-2155c3829ee8    INFO    { statusCode: 200, body: '{"1 = 1":1}' }
2020-07-16T20:56:21.915Z    e7a51db9-c36e-463b-ba82-2155c3829ee8    INFO    { statusCode: 200, body: '{"1 = 1":1}' }
2020-07-16T20:56:21.926Z    e7a51db9-c36e-463b-ba82-2155c3829ee8    INFO    Connected as id 87
END RequestId: e7a51db9-c36e-463b-ba82-2155c3829ee8
REPORT RequestId: e7a51db9-c36e-463b-ba82-2155c3829ee8  Duration: 13.89 ms  Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 19 MB

and here without any data

START RequestId: c539be40-6800-436f-a29e-5e3846876e6f Version: $LATEST
END RequestId: c539be40-6800-436f-a29e-5e3846876e6f
REPORT RequestId: c539be40-6800-436f-a29e-5e3846876e6f  Duration: 199.15 ms Billed Duration: 200 ms Memory Size: 128 MB Max Memory Used: 17 MB

here is my code

const mysql = require('mysql');

exports.handler = async (event) => {
    
    const connection = mysql.createConnection({
    host: process.env.RDS_HOST,
    user: process.env.USER,
    password: process.env.RDS_PASSWORD,
    database: process.env.RDS_DB_NAME,
    port: 3306,
    multipleStatements: false
    });

    await connection.connect(function(err) {
        if (err) {
            console.error('Error connecting: ' + err.stack);
            return;
        }
    
        console.log('Connected as id ' + connection.threadId);
    });
    
    await connection.query('SELECT 1 = 1', function (error, results, fields) {
        if (error) throw error;
        connection.end();
        const response = {
                statusCode: 200,
                body: JSON.stringify(results[0]),
            };
        console.log(response);
        return response;
    });
};

Upvotes: 0

Views: 608

Answers (1)

Evert
Evert

Reputation: 99861

Your MySQL library uses callbacks, not promises. Putting await in front of a callback-based API will not do anything.

You should upgrade your mysql library that works with promises instead.

If it helps, I wrote a bunch of stuff about better alternatives here:

https://evertpot.com/executing-a-mysql-query-in-nodejs/

Upvotes: 2

Related Questions