【问题标题】:Can you publish multiple messages to an SNS topic using an AWS Lambda function backed by node.js 8.10?您可以使用 node.js 8.10 支持的 AWS Lambda 函数将多条消息发布到 SNS 主题吗?
【发布时间】:2018-11-11 15:39:52
【问题描述】:

有一个关于如何发布单条消息的相关问题:Can you publish a message to an SNS topic using an AWS Lambda function backed by node.js?

但是,我的问题与发布多条消息有关。 我使用的是节点 8.10,我的处理程序是异步的。

【问题讨论】:

  • 您试过之后遇到问题了吗?
  • 是的,我在没有 async+await 的情况下工作,当我使处理程序异步时它失败了

标签: node.js aws-lambda amazon-sns


【解决方案1】:

您可以使用Promise.all() 功能来封装对sns.publish 的多个调用。

  1. 创建一个返回 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 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 将在所有消息发布后调用(成功与否)

【讨论】:

    【解决方案2】:

    相关问题使用context.done,它将在进行第二次调用之前结束 lambda。使用

    sns.publish(params, function(err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else     console.log(data);           // successful response
    });
    

    您可以拨打更多电话,例如

    sns.publish(params2, function(err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else     console.log(data);           // successful response
    });
    

    您是想使用async.waterfall、嵌套调用还是让它们异步执行取决于您。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2021-10-18
      • 2021-02-15
      • 2020-07-08
      • 2019-11-05
      • 2017-02-22
      相关资源
      最近更新 更多