AWS SNS 不在 lambda 上工作,但在本地工作

AWS SNS not working from lambda, but working locally

我遇到了无法自己解决的问题。我的 lambda 函数在本地调用时按预期工作,但在从 AWS Lambda 调用时它不发送文本消息。它也不记录任何错误。

这是我的代码,我只给私人内容加了星号:

import request from 'request';
import AWS from "aws-sdk";

const options = {***};
const sentAlert = async msg => {
  const sns = new AWS.SNS();
  await sns.publish({
    Message: msg,
    PhoneNumber: '***',
    MessageAttributes: {
      'AWS.SNS.SMS.SenderID': {
        'DataType': 'String',
        'StringValue': '***'   
      }
    }
  }, function (err, data) {
  if (err) {
    console.log(err.stack);
    return;
  }
  });
  console.log('sms sent');
};

export const getAlert = async (event, context, callback) => {
  request(options, (err, res, body) => {
    if (err) { return console.log('error: ', err); }
    if (body.length === 0 ) { return }
    console.log(`***`);
    const optionsId = {*** };
    request(optionsId, (err, res, body) => { 
      const msg = body.current.indexes[0].description;
      console.log('msg: ', msg);
      sentAlert(msg);
    });
  });
};

我使用 serverless invoke local --function getSmogAlert 在本地测试它,它按预期工作,我从 AWS 收到短信,但是当我用 serverless invoke --function getSmogAlert 调用它时 - 它 returns 为空并且没有'发送任何短信。 我在使用 Nexmo 时遇到过类似的问题,并认为 AWS.SNS 可能会对我有所帮助,但没有。

有什么帮助吗?

正如我在评论中所写,我认为您混淆了执行中的承诺和回调。试试这个改变:

const options = {***};
const sentAlert = (msg, callback) => {
  const sns = new AWS.SNS();
  await sns.publish({
    TopicArn: ***
    Message: msg,
    PhoneNumber: '***',
    MessageAttributes: {
      'AWS.SNS.SMS.SenderID': {
        'DataType': 'String',
        'StringValue': '***'   
      }
    }
  }, function (err, data) {
  if (err) {
    console.log(err.stack);
    callback(err);
  }
  });
  console.log('sms sent');
  callback(null)
};

export const getAlert = (event, context, callback) => {
  request(options, (err, res, body) => {
    if (err) { 
      console.log('error: ', err);
      callback(err); 
    }
    if (body.length === 0 ) {
      console.log('Got no body!') 
      callback(null) 
    }
    console.log(`***`);
    const optionsId = {*** };
    request(optionsId, (err, res, body) => {
      if (err) {
        console.log(err.stack);
        callback(err);
      } 
      const msg = body.current.indexes[0].description;
      console.log('msg: ', msg);
      sentAlert(msg, callback);
    });
  });
};

但总的来说,我更愿意使用 AWS Lambda nodejs8.10 映像支持的 async/await 机制。这将使您的代码简单易懂。