Alex Schwartz
Alex Schwartz

Reputation: 19

Can you publish multiple messages to an SNS topic using an AWS Lambda function backed by node.js 8.10?

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

Answers (2)

guysigner
guysigner

Reputation: 2922

You can use the Promise.all() feature to encapsulate multiple calls to sns.publish.

  1. Create a one-notification-publish function that returns Promise:

.

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);
        }
    });
  });
}
  1. Create and send notifications in parallel:

// 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

K Mo
K Mo

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

Related Questions