简体   繁体   English

您是否可以使用由node.js 8.10支持的AWS Lambda函数将多个消息发布到SNS主题?

[英]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? 关于如何发布单个消息,存在一个相关问题: 您是否可以使用由node.js支持的AWS Lambda函数将消息发布到SNS主题?

However, my question is related to publish more than one message. 但是,我的问题与发布多个消息有关。 I am using node 8.10 and my handler is asynchronous. 我正在使用节点8.10,并且我的处理程序是异步的。

The related question uses context.done , which would end the lambda before making a second call. 相关问题使用context.done ,它将在发出第二个调用之前结束lambda。 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, eg 您可以拨打更多电话,例如

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. 是否要使用async.waterfall ,嵌套调用还是让它们异步进行取决于您。

You can use the Promise.all() feature to encapsulate multiple calls to sns.publish. 您可以使用Promise.all()功能来封装对sns.publish的多次调用。

  1. Create a one-notification-publish function that returns Promise: 创建一个返回通知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) 发布所有消息后(成功与否),将调用callback

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM