0

I have the following Lambda.

const AWS = require('aws-sdk');
exports.lambdaHandler = async (event, context) => {
    console.log("START v5");
    const SNSarn = process.env.SNS;
    console.log(SNSarn);
    const snsParams={
        Message: "test",
        TopicArn: SNSarn
    };
    const SNS = new AWS.SNS();
    SNS.publish(snsParams, function(err,data){
        console.log ("We are in the callback!");
        if (err) {
            console.log('Error sending a message', err);
            context.done(err,'We have errors');
        }

        console.log('Sent message');
        context.done(null,"Done!");
    });
    console.log('END');
};

When I run it locally, ther lambda performs as expected and pushes a message to SNS.
For some reason, I do not see the console.log that is in the callback.
How do I fix it so I can also see logs from callbacks?

Below is the output I do see:

START RequestId: ff2691cc-a7d0-40f2-a956-277bxxxx21d Version: $LATEST
2021-11-15T21:17:17.968Z    ff2691cc-a7d0-40f2-a956-277bxxxx821d    INFO    START v5
2021-11-15T21:17:17.970Z    ff2691cc-a7d0-40f2-a956-277bxxxx821d    INFO    arn:aws:sns:us-east-1:xxxxxxxxxxxxxxx:tooktook-topic
2021-11-15T21:17:17.992Z    ff2691cc-a7d0-40f2-a956-277bxxxx821d    INFO    END
END RequestId: ff2691cc-a7d0-40f2-a956-277bxxxx821d
REPORT RequestId: ff2691cc-a7d0-40f2-a956-277bxxxx821d  Init Duration: 0.19 ms  Duration: 261.33 ms Billed Duration: 300 ms Memory Size: 128 MB Max Memory Used: 128 MB 
John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278
  • Looks like you have to use an `async` function in the callback. https://stackoverflow.com/questions/47806294/wait-for-aws-sns-publish-callback-to-return-a-value-to-calling-method/51315070 – sagar1025 Nov 16 '21 at 01:23

1 Answers1

0

In method SNS.publish, you are using callback which is asynchronous in nature and there is a possibility of successful lambda execution before callback is even called. SNS takes a bit of time for execution. you need to use async/ await in this case. AWS APIs support promises.

Here is an example:

const AWS = require('aws-sdk');
exports.lambdaHandler = async (event, context) => {
    console.log("START v5");
    const SNSarn = process.env.SNS;
    console.log(SNSarn);
    const snsParams={
        Message: "test",
        TopicArn: SNSarn
    };
    const SNS = new AWS.SNS();
   try {
     const data = await SNS.publish(snsParams).toPromise();
      console.log('Sent Message');
      context.done(null, 'Done');
    } catch (error) {
       console.log('We are in the callback!');
       context.done(err, 'We have errors');
    }
    console.log('END');
};
Bhavya Dhiman
  • 282
  • 2
  • 15