如何过滤DynamoDB Scan结果数组,仅保留有效返回值
Solution
The core issue is that your Promise.all is collecting all resolved values—including the invalid 'x' or undefined entries. To get only the valid ['a','b'] arrays, you just need to filter the final result set and fix a common closure bug in your loop.
Step-by-Step Fixes:
- Fix the loop variable: Use
letinstead ofvarforindexin your for loop. This ensures each iteration has its own copy of the index (avoids a bug where all scan operations end up using the final index value). - Filter invalid results: After
Promise.allresolves, filter out any values that aren't valid arrays matching your desired format.
Modified Code:
var results = []; var array = ["a", "b"]; // Use let for index to fix closure issue for (let index = 1; index <= 5; ++index) { var params1 = { TableName: "MyCatTable", FilterExpression: "#rule=:rule", ExpressionAttributeNames: { "#rule": "rule" }, ExpressionAttributeValues: { ":rule": String(index) } }; results.push( dynamodb.scan(params1).promise() .then(function (data) { if (data.Items.length == 2) { var uw = []; console.log("Entered"); for (var i = 0; i < 2; i++) { if (array.indexOf(data.Items[i].category) >= 0) { console.log("pushing"); uw.push(data.Items[i].category); } } // Return valid array only if it has both elements return uw.length === 2 ? uw : null; } else { // Return null for invalid cases return null; } }) ); } Promise.all(results) .then((data) => { // Filter out null/undefined and keep only valid arrays const validResults = data.filter(result => Array.isArray(result) && result.length === 2); console.log("----------------------"); console.log(validResults); // Output: [ ['a','b'], ['a','b'] ] }) .catch(err => { console.log(err); });
Explanation:
- Loop Variable Fix: Using
letin the for loop creates a new binding forindexin each iteration, so each scan operation uses the correct value ofindexwhen it runs. - Filtering: The
filtermethod checks if each result is an array with exactly 2 elements (matching your valid['a','b']format). This removes anynull,'x', orundefinedentries from the final output.
If you prefer to keep returning 'x' instead of null, adjust the filter to:
const validResults = data.filter(result => result !== 'x' && Array.isArray(result));
内容的提问来源于stack exchange,提问作者user3872094
相关产品推荐
相关产品推荐

