I'm struggling with a simple AWS Lambda function that should publish some messages to a SNS topic.
My email address is subscribed to the topic and the subscription has been confirmed.
The topic is in the same region as my lambda function.
The function is associated to an IAM role that has two policies attached:
- the default policy AWSLambdaBasicExecutionRole
- another policy that allows the function to write to my SNS topic
Policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "sns:Publish",
"Resource": "arn:aws:sns:eu-west-1:XXXXXXXXXXXX:YYYYYYYYYYYYYYYYYYY"
}
]
}
Here is my function code, developed on Cloud9.
const AWS = require("aws-sdk");
const sns = new AWS.SNS({region:'eu-west-1'});
exports.handler = async (event, context, callback) => {
const apiResponse = new Promise((resolve, reject) => {
setTimeout(() => resolve(['one', 'two', 'three']), 500)
});
const messages = await apiResponse;
const promises = [];
messages.forEach(txt => {
promises.push(sns.publish({
Message: txt,
Subject: txt,
TopicArn: 'arn:aws:sns:eu-west-1:xxxxxxxxxxxx:MyWebsiteContactForm'
}).promise());
});
console.log(promises);
Promise.all(promises,
function (values) {
console.log(values);
callback(null, values);
},
function(err) {
console.error(Error(err));
callback(Error(err));
}
);
};
The result of executing this code is just this expected output, but it never logs anything inside Promise.all()
.
[ Promise { <pending> },
Promise { <pending> },
Promise { <pending> } ]
It's like if Lambda terminates before resolving the promises, but I cannot figure out why. I used Promise.all()
as suggested here
Thanks in advance