Question:
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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
'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:
1 2 3 4 5 6 7 8 9 10 11 |
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 |
Answer:
Your lambda is exiting before completing the promise. To circumvent this you can use async-await
:
1 2 3 4 5 6 |
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(...)