How to handle UnprocessedItems using AWS JavaScript SDK (dynamoDB)?
This is my code sample using the "await" syntax. So this code must be in an async function. It does a random delay before retry.
do {
batchWriteResp = await dynamo.batchWriteItem({RequestItems:batchWriteItems}).promise()
if (Object.keys(batchWriteResp.UnprocessedItems).length>0) {
batchWriteItems = batchWriteResp.UnprocessedItems
// delay a random time between 0.5~2.5 seconds
const delay = Math.floor(Math.random() * 2000 + 500)
await new Promise(resolve => setTimeout(resolve, delay));
} else {
break
}
} while (true)
@Daniela Miao, Thanks for sharing the solution.
We can add one code block in your posted code which will avoid exception from DynamoDB. This will check if params.RequestItems has Unprocessed data before requesting the DynamoDB for batch write again.
//db is AWS.DynamoDB Client
var processItemsCallback = function(err, data) {
if (err) {
//fail
} else {
var params = {};
params.RequestItems = data.UnprocessedItems;
/*
* Added Code block
*/
if(Object.keys(params.RequestItems).length != 0) {
db.batchWriteItem(params, processItemsCallback);
}
}
};
db.batchWriteItem(/*initial params*/, processItemsCallback);