为什么AWS Lambda函数返回null?

时间:2019-08-17 22:08:24

标签: node.js amazon-web-services promise aws-lambda

我的AWS Lambda函数通过SNS发送电子邮件,但是在Lambda控制台中响应为null。我使用了AWS提供的蓝图,并使用Node.js 10.x将代码放入Lambda处理程序中。

https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/sns/sns_publishtotopic.js

我在使用node.js中的promises方面经验不足,而我对Stack Overflow的研究似乎表明这可能是问题所在。

'use strict';

var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'us-west-2'});


exports.handler = (event, context, callback) => {
// Create publish parameters
var params = {
            //Message: `The fluid level is low on your Knight system: ${event.my_volume} mL.`,
            Message: `The fluid level is low on your Knight system.`,
            Subject: `Low Fluid Level Alert - Knight`,
            TopicArn: `arn:aws:sns:us-west-2:468820349153:MyLowVolumeTopic`,
        };

// Create promise and SNS service object
var publishTextPromise = new AWS.SNS({apiVersion: '2010-03-31'}).publish(params).promise();

// Handle promise's fulfilled/rejected states


publishTextPromise.then(
  function(data) {
    console.log("Message: " + params.Message);
    console.log("Sent to the topic: " + params.TopicArn);
    console.log("MessageID is " + data.MessageId);
  }).catch(
    function(err) {
    console.error(err, err.stack);
  });
};

结果是我收到的电子邮件不一致,并且在Lambda控制台中看到空响应。这是一个示例日志结果:

Response: null
Request ID: "9dcc8395-5e17-413a-afad-a86b9e04fb97"

Function Logs:
START RequestId: 9dcc8395-5e17-413a-afad-a86b9e04fb97 Version: $LATEST
2019-08-17T21:44:31.136Z    9dcc8395-5e17-413a-afad-a86b9e04fb97    Message: The fluid level is low on your Knight system.
2019-08-17T21:44:31.136Z    9dcc8395-5e17-413a-afad-a86b9e04fb97    Sent to the topic: arn:aws:sns:us-west-2:468820349153:MyLowVolumeTopic
2019-08-17T21:44:31.136Z    9dcc8395-5e17-413a-afad-a86b9e04fb97    MessageID is cb139fb6-5d37-574e-9134-ca642a49fde5
END RequestId: 9dcc8395-5e17-413a-afad-a86b9e04fb97
REPORT RequestId: 9dcc8395-5e17-413a-afad-a86b9e04fb97  Duration: 1367.98 ms    Billed Duration: 1400 ms    Memory Size: 128 MB Max Memory Used: 75 MB

1 个答案:

答案 0 :(得分:2)

您的lambda在完成承诺之前就退出了。为了避免这种情况,您可以使用async-await

exports.handler = async (event, context, callback) => {
    const data = await publishTextPromise;
    //maybe some console log here
    return data;
}

或者,您可以 返回 应许return publishTextPromise.then(...).catch(...)