0

我有一个我自己无法解决的问题。我的 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- 它调用它时,它返回 null 并且不发送任何文本消息。我在使用 Nexmo 时遇到过类似的问题,并认为 AWS.SNS 可能会帮助我,但不是。

请问有什么帮助吗?

4

1 回答 1

0

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

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 机制。这将使您的代码简单且易于推理。

于 2018-10-24T06:47:22.617 回答