5

My AWS Lambda function sends an email through SNS, but the response is null in the Lambda console. I used a blueprint provided by AWS and put the code in a Lambda handler using Node.js 10.x.

https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/sns/sns_publishtotopic.js

I am not that experienced in the use of promises in node.js and my research on Stack Overflow seems to indicate that could be the problem here.

'use strict';

var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'us-west-2'});


exports.handler = (event, context, callback) => {
// Create publish parameters
var params = {
            //Message: `The fluid level is low on your Knight system: ${event.my_volume} mL.`,
            Message: `The fluid level is low on your Knight system.`,
            Subject: `Low Fluid Level Alert - Knight`,
            TopicArn: `arn:aws:sns:us-west-2:468820349153:MyLowVolumeTopic`,
        };

// Create promise and SNS service object
var publishTextPromise = new AWS.SNS({apiVersion: '2010-03-31'}).publish(params).promise();

// Handle promise's fulfilled/rejected states


publishTextPromise.then(
  function(data) {
    console.log("Message: " + params.Message);
    console.log("Sent to the topic: " + params.TopicArn);
    console.log("MessageID is " + data.MessageId);
  }).catch(
    function(err) {
    console.error(err, err.stack);
  });
};

The result is that I receive the email message inconsistently and see a null response in the Lambda console. Here is a sample log result:

Response: null
Request ID: "9dcc8395-5e17-413a-afad-a86b9e04fb97"

Function Logs:
START RequestId: 9dcc8395-5e17-413a-afad-a86b9e04fb97 Version: $LATEST
2019-08-17T21:44:31.136Z    9dcc8395-5e17-413a-afad-a86b9e04fb97    Message: The fluid level is low on your Knight system.
2019-08-17T21:44:31.136Z    9dcc8395-5e17-413a-afad-a86b9e04fb97    Sent to the topic: arn:aws:sns:us-west-2:468820349153:MyLowVolumeTopic
2019-08-17T21:44:31.136Z    9dcc8395-5e17-413a-afad-a86b9e04fb97    MessageID is cb139fb6-5d37-574e-9134-ca642a49fde5
END RequestId: 9dcc8395-5e17-413a-afad-a86b9e04fb97
REPORT RequestId: 9dcc8395-5e17-413a-afad-a86b9e04fb97  Duration: 1367.98 ms    Billed Duration: 1400 ms    Memory Size: 128 MB Max Memory Used: 75 MB

1 Answer 1

5

Your lambda is exiting before completing the promise. To circumvent this you can use async-await:

exports.handler = async (event, context, callback) => {
    const data = await publishTextPromise;
    //maybe some console log here
    return data;
}

OR, You can return the promise, return publishTextPromise.then(...).catch(...)

Sign up to request clarification or add additional context in comments.

1 Comment

This is correct with one slight alteration: const data = await publishTextPromise; (because publishTextPromise is not a function).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.