Home Blog JavaScript Node.js SQS sendMessage promise chaining on AWS Lambda
Node.js SQS sendMessage promise chaining on AWS Lambda
JavaScript
Written by Dicky   
Friday, 05 October 2018 15:40
AddThis Social Bookmark Button

I encountered a weird behavior when writing a AWS Lambda on Node.js when it involved SQS sendMessage() method.

The lambda will exit the function before it's sending the SQS message which give me the wrong return value. I believe this is due to the call back function that's required when calling the sendMessage() method. I found out that the callback will return an AWS.Request object where you use a request.promise() and request.then(function(data) { ... }, function(error) { ... });

I fixed this by using promise chaining as shown in the example below.

async sendMessage(jsonObject, correlationId) {
 try {
 var params = {
 MessageAttributes: {
 "correlationId": {
 DataType: "String",
 StringValue: correlationId
 }
 },
 DelaySeconds: 0,
 MessageBody: JSON.stringify(jsonObject),
 QueueUrl: this._queueURL
 };
 await sqsClient.sendMessage(params).promise().then(function(data) {
 log.info("Success sending SQS Message: " + data.MessageId, { correlationId });
 return true;
 }, function(error) {
 log.error("Error while sending SQS Message. Error: " + err.message, { correlationId, err });
 return false;
 }
 );
 } catch (error){
 log.error("Error while sending SQS Message. Error: " + error.message, { correlationId, error });
 return false;
 }
 return true;
}

With the code above, it's guaranteed that the message is sent before exiting the function. I would also recommend to read the following article regarding await, promise and call backs function in node.js.