DynamoDB的putItem回调函数不起作用

14
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没有工作,回调函数没有被调用。我已经给了该用户角色的完全访问权限,但函数仍未被调用。

2个回答

25

假设您正在使用 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在这里的回答:https://dev59.com/AKbja4cB1Zd3GeqPh4ps 应该会有所帮助。 - AlleyOOP
无论如何,这将返回一个200状态码,这可能不是您想要的。 - Harrison Cramer
2
@HarryCramer 响应结果可以在 //在此处处理您的结果 中进行修改。当然,我没有写下如何处理结果和修改响应,因为这取决于使用情况。 - Ricky Mo

2
这个错误的另一个可能原因是使用 AWS.DynamoDB.DocumentClient() 而不是 AWS.DynamoDB()。在这种情况下,DocumentClient 使用 put 方法而不是 putItem。
当出现这种情况时,我一直检查异步和 Promise 代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接