发送SNS推送lambda - 没有消息?

时间:2016-07-31 16:35:34

标签: amazon-web-services push-notification aws-lambda

我的lambda函数有问题。它获取设备的数据并发送推送通知(有人将您添加到朋友的信息)。但是,经常会发送推送通知未发送。有时,我必须多次激活该功能(通过同时点击按钮)使其发送推送通知。在Lambda中测试以下函数时,它不会发送任何推送通知。可能是什么问题?

提前谢谢你, 约翰

console.log("Loading friend-request function");
var AWS = require("aws-sdk");

exports.handler = function(event, context) {

    var senderID = event.senderID;
    var receiverID = event.receiverID;
    var message = event.message;

    var eventText = JSON.stringify(event);
    console.log("Received event:", eventText);
    var sns = new AWS.SNS();
    var params = {
        Message: message, 
        Subject: "Test SNS From Lambda",
        TargetArn: receiverID
    };

    context.succeed(message); 
    sns.publish(params, context.done);

};

1 个答案:

答案 0 :(得分:2)

请记住,sns.publish()函数是异步的,即您必须等待它才能完成,然后才能调用context.succeed()。否则,Lambda函数可能会在消息发布之前终止。

exports.handler = function(event, context) {
    // same as before...

    var params = {...}

    // do not call context.succeed() yet

    sns.publish(params, function(err, data) {
        if (err) {
            console.log('Failed to publish SNS message');
            context.fail(err);
        }
        else {
            console.log('SNS message published successfully');
            context.succeed(data);
        }
    });
};