从 lambda (node js) 发布 SNS 消息导致超时错误

Publishing SNS message from lambda (node js) result in timeout error

我使用了从 AWS 提供的示例稍作修改的非常简单的代码:

    exports.handler = async (event) => {
        // Load the AWS SDK for Node.js
        var AWS = require('aws-sdk');
        // Set region
        AWS.config.update({region: 'ap-southeast-2'});
    
        // Create publish parameters
        var params = {
            Message: 'This is a sample message',
            Subject: 'Test SNS From Lambda',
            TopicArn: 'arn:aws:sns:ap-southeast-2:577913011449:TestTopic'
        };
    
        // Create promise and SNS service object
        var publishTextPromise = new AWS.SNS().publish(params).promise();
    
        let response = {
            statusCode: 200,
            body: JSON.stringify('Hello from Lambda!'),
        };
    
        // Handle promise's fulfilled/rejected states
        publishTextPromise.then(
            function(data) {
                console.log("Message ${params.Message} send sent to the topic ${params.TopicArn}");
                console.log("MessageID is " + data.MessageId);
                response.result = 'Success';
            }).catch(
                function(err) {
                console.error(err, err.stack);
                response.result = 'Error';
            });
    
        
        return response;
    };

我在测试此服务时遇到超时错误。 3秒为限。

由于这是一个非常简单的过程,我认为执行时间不应超过 3 秒。

我已经检查了我的 IAM 设置并授予我的配置文件(管理员配置文件)以完全访问 SNS 服务。但错误仍然存​​在。我想知道这里出了什么问题,我该如何解决?

我不确定你为什么会超时,但你的代码不应该按你预期的方式工作。

看到您 return 在 .then() 代码之外进行响应,这意味着您的代码将 return 在 .then() 代码甚至 运行(承诺是异步的)。

由于您已经在使用 Node 8,因此最好使用 async/await 而不是使用旧的 .then().catch() 方法。

我对你的代码进行了一些重构,它工作得很好。为了您的方便,我保留了原始参数。查看代码如何更易于阅读和调试。

'use strict';

// Load the AWS SDK for Node.js
const AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'ap-southeast-2'});

const sns = new AWS.SNS()

module.exports.handler = async (event) => {

  const params = {
    Message: 'This is a sample message',
    Subject: 'Test SNS From Lambda',
    TopicArn: 'arn:aws:sns:ap-southeast-2:577913011449:TestTopic'
  };

  let response = {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda!'),
  };
  try {
    const data = await sns.publish(params).promise();
    response.messageId = data.MessageId,
    response.result = 'Success'
  } catch (e) {
    console.log(e.stack)
    response.result = 'Error'
  }
  return response

};

如果出于某种原因不想使用 async/await,则需要将函数的 return 移动到 .then() 代码中,以及 return 一旦 promise 被调用,像这样:

'use strict';

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'ap-southeast-2''});

// Create publish parameters
var params = {
    Message: 'This is a sample message',
    Subject: 'Test SNS From Lambda',
    TopicArn: 'arn:aws:sns:ap-southeast-2:577913011449:TestTopic'
};

module.exports.handler = async (event) => {

  // Create promise and SNS service object
  var publishTextPromise = new AWS.SNS().publish(params).promise();

  let response = {
      statusCode: 200,
      body: JSON.stringify('Hello from Lambda!'),
  };

  // Handle promise's fulfilled/rejected states
  return publishTextPromise.then(
      function(data) {
          console.log("Message ${params.Message} send sent to the topic ${params.TopicArn}");
          console.log("MessageID is " + data.MessageId);
          response.result = 'Success';
          return response;
      }).catch(
          function(err) {
          console.error(err, err.stack);
          response.result = 'Error';
          return response
      });

};

虽然我强烈建议您使用方法 1。