1

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.

Alex Schwartz
  • 11
  • 1
  • 2

2 Answers2

1

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)

guysigner
  • 2,822
  • 1
  • 19
  • 23
0

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.

K Mo
  • 2,125
  • 8
  • 16