【问题标题】:Not able to access AWS DynamoDb from Lambda function无法从 Lambda 函数访问 AWS DynamoDb
【发布时间】:2020-04-26 21:21:45
【问题描述】:

无法从 Lambda 函数访问 AWS DynamoDb。

Lambda 函数:

'use strict';
const AWS = require('aws-sdk');
AWS.config.update({region: 'ap-southeast-2'});

const getUser = async function () {
    console.log('getUser() invoked');
    const documentClient = new AWS.DynamoDB.DocumentClient();
    const params = {
        TableName: 'Users',
        Key: {
          "UserId": "A001"
        }
    };
    console.log('params ', params);
    documentClient.get(params, function (err, data) {
        console.log('============>');
        if (err) {
            console.log('error ', err);
            return err;
        }
        console.log('success ', data);
        return data;
    });
};

exports.handler = async (event, context, callback) => {
    // TODO implement
    console.log('event ', event);
    const data = await getUser();
    console.log('=============> data ', data);
};

在测试 Lambda 函数时,打印的数据未定义。它正在打印参数,但不打印错误和成功。

【问题讨论】:

  • CloudWatch Logs 中是否有任何错误?
  • 您的 Lambda 函数是否配置为使用 VPC?如果是这样,这意味着除非提供 NAT 网关或 VPC 端点,否则它无法访问 Internet。
  • 没有 lambda 函数未配置为使用 VPC。我正在 AWS 管理控制台中尝试。我需要在 AWS 控制台中配置 VPC 吗?
  • CloudWatch 中未报告错误。

标签: amazon-web-services aws-lambda amazon-dynamodb


【解决方案1】:

你在这里对回调和承诺有些困惑,你现在的方式是你没有将数据传递到外面。

const getUser = async function () {
  console.log('getUser() invoked');
  const documentClient = new AWS.DynamoDB.DocumentClient();
  const params = {
      TableName: 'Users',
      Key: {
        "UserId": "A001"
      }
  };
  console.log('params ', params);
  try {
    const data = await documentClient.get(params).promise();
    console.log('============>');
    console.log('success ', data);
    return data;
  } catch(err) {
    console.log('error ', err);
    throw err;
  }
};

to more about callback and promises check

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2020-08-01
    • 2016-05-27
    • 2020-09-01
    • 2018-06-25
    • 1970-01-01
    相关资源
    最近更新 更多