SleeplessFox
SleeplessFox

Reputation: 183

DynamoDb UpdateItem runs twice

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?

Upvotes: 1

Views: 841

Answers (1)

Dori Aviram
Dori Aviram

Reputation: 322

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)

Upvotes: 5

Related Questions