DynamoDb UpdateItem chạy hai lần
Oct 24 2020
Khi tôi cập nhật một mục thông qua cập nhật (updateItem) thì hàm cập nhật được gọi hai lần và giá trị của tôi sẽ được cộng thêm hai lần. Tôi sử dụng async / await và nó sẽ hoạt động.
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;
}
Đầu ra bảng điều khiển chỉ được in một lần
###### updateDb
Nhưng kết quả đầu ra
console.log("updateDb:", JSON.stringify(data.Attributes, null, 2));
được in 2 lần và giá trị thời lượng cũng được cộng 2 lần vào giá trị từ db.
Nó chỉ nên được gọi một lần ... Làm ơn có ai biết lỗi của tôi ở đây không?
Trả lời
3 DoriAviram Oct 25 2020 at 08:11
Nó giống như vậy bởi vì bạn sử dụng phương thức gọi lại và lời hứa cùng nhau, hãy cố gắng chỉ sử dụng phương pháp hứa hẹn.
Thay thế:
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();
Với:
await ddb.update(param).promise().then(r => {
console.log("updateDb:", JSON.stringify(data.Attributes, null, 2))
}).catch(e => {
console.log("Error", e);
});
Cũng tương tự như Node JS + AWS Promise Triggered Twice (chỉ trong dịch vụ ses)