Reputation: 19
There is a related question regarding how to publish s single message: Can you publish a message to an SNS topic using an AWS Lambda function backed by node.js?
However, my question is related to publish more than one message. I am using node 8.10 and my handler is asynchronous.
Upvotes: 1
Views: 2879
Reputation: 2922
You can use the Promise.all() feature to encapsulate multiple calls to sns.publish.
.
function onePublishPromise(notificationParams){
return new Promise((resolve, reject) => {
sns.publish(notificationParams, function(err, data) {
if (err) {
console.error("Unable to send notification message. Error JSON:", JSON.stringify(err, null, 2));
reject(err);
} else {
console.log("Results from sending notification message: ", JSON.stringify(data, null, 2));
resolve(null);
}
});
});
}
// Create notifications params
const notifications = [
{
Subject: 'A new notification',
Message: 'Some message',
TopicArn: 'arn:aws:sns:us-west-1:000000000:SomeTopic'
}
// , ...
];
// Send all notifications
const notificationsDelivery = notifications.map(onePublishPromise);
// Wait for delivery results
Promise.all(notificationsDelivery).then(callback).catch(callback);
callback
will be called after all messages published (successfully or not)
Upvotes: 1
Reputation: 2155
The related question uses context.done
, which would end the lambda before making a second call. Using
sns.publish(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
you can make more calls, e.g.
sns.publish(params2, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Whether you want to use async.waterfall
, nest the calls or let them go asynchronously is up to you.
Upvotes: 0