DynamoDb UpdateItem runs twice

只愿长相守 提交于 2020-12-13 03:40:36

问题


When I update an item via update (updateItem) then the update function is called twice and my value will be added two times. I use async/await and it should work.

var ddb = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10' });

async function updateUserGame(tablePostfix, gameId, durationinMin) {
    console.log("###### updateUserGame")

    var tableUserGames = tableUserGamesWithoutPostfix + tablePostfix;

    expressions = {
        ":duration": parseInt(durationinMin)
    }
    updateExpressions = "set playDuration = playDuration + :duration";

    var params = {
        TableName: tableUserGames,
        Key: {
            id: parseInt(gameId)
        },
        ExpressionAttributeValues: expressions,
        UpdateExpression: updateExpressions,
        ReturnValues: "ALL_NEW"
    };

    return await updateDb(params);
}

async function updateDb(params) {
    console.log("###### updateDb")
    var savedItem;

    // Call DynamoDB to add the item to the table
    await ddb.update(params, function(err, data) {
            if (err) {
                console.log("Error", err);
            } else {
                console.log("updateDb:", JSON.stringify(data.Attributes, null, 2));

                savedItem = data.Attributes;
            }
        }).promise();

    return savedItem;
}

Console output is printed just one time

###### updateDb

But the result output

 console.log("updateDb:", JSON.stringify(data.Attributes, null, 2));

is printed 2 times and the duration value is added 2 times too to the value from the db.

It should just called one time... Please anybody know my mistake here?


回答1:


It looks like its because you using method callback and promise together, try to use only the promise approach.

Replace:

await ddb.update(params, function(err, data) {
    if (err) {
        console.log("Error", err);
    } else {
        console.log("updateDb:", JSON.stringify(data.Attributes, null, 2));
        savedItem = data.Attributes;
    }
}).promise();

With:

await ddb.update(param).promise().then(r => {
    console.log("updateDb:", JSON.stringify(data.Attributes, null, 2))
}).catch(e => {
    console.log("Error", e);
});

Also similar to Node JS + AWS Promise Triggered Twice (only in ses service)



来源:https://stackoverflow.com/questions/64518137/dynamodb-updateitem-runs-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!