【问题标题】:dynamodb putItem callback function not workingdynamodb putItem 回调函数不起作用
【发布时间】:2022-02-06 11:51:45
【问题描述】:
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = async (event) => {

    var note = {};
    note.noteid = new Date().getTime();
    note.content = event.queryStringParameters["content"];

    var res = {};

    const response = {
        statusCode: 200,
        body: JSON.stringify(note),
    };

    var obj = {
        'TableName':'notes',
        'Item': {
          'note_id': {
            S: '2'
          },
          'name': {
            S: 'content'
          }
        },
        'ReturnConsumedCapacity': "TOTAL"
    };

    dynamodb.putItem(obj, function(err,result){
        console.log('function called!!');
        console.log(err);

        return response;
    });

};

我的putItem 不工作,回调函数没有被调用。我已授予此用户角色的完全访问权限,但仍未调用函数。

【问题讨论】:

    标签: javascript amazon-dynamodb


    【解决方案1】:

    假设您使用的是 AWS Lambda。由于您使用的是async/await 模式,http 响应最终是async (event) => {} 返回的内容。在你的情况下,这没什么。你打电话给putItem,但没有等到。 async (event) => {} 之后立即不返回任何内容。由于函数已经返回,您的putItem 调用没有机会回调。

    您应该将putItem 调用转换为promiseawait。然后处理结果并返回http响应。

    const AWS = require('aws-sdk');
    const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
    
    exports.handler = async (event) => {
    
        var note = {};
        note.noteid = new Date().getTime();
        note.content = event.queryStringParameters["content"];
    
        var res = {};
    
        const response = {
            statusCode: 200,
            body: JSON.stringify(note),
        };
    
        var obj = {
            'TableName':'notes',
            'Item': {
              'note_id': {
                S: '2'
              },
              'name': {
                S: 'content'
              }
            },
            'ReturnConsumedCapacity': "TOTAL"
        };
    
        try
        {
            var result = await dynamodb.putItem(obj).promise();
            //Handle your result here!
        }
        catch(err)
        {
            console.log(err);
        }
        return response;
    };
    

    【讨论】:

    • Felipe 在这里的回答:stackoverflow.com/questions/47140031/… 应该有帮助
    • 无论如何这将返回一个 200 状态码,这可能不是你想要的
    • @HarryCramer 可以在//Handle your result here 中修改响应结果。当然我没有写下如何处理结果和修改响应,因为这取决于用例。
    【解决方案2】:

    此错误的另一个可能原因是使用 AWS.DynamoDB.DocumentClient() 而不是 AWS.DynamoDB(); 在这种情况下,DocumentClient 使用 put 方法而不是 putItem

    当这是原因时,我一直在检查异步和承诺代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多