我正在编写一个执行以下功能的动态代码。
基本上尝试在DynamoDb中创建一个组。
这是第一步和第二步,我能够做到。但是进入第3步我已经循环并且在循环内部必须执行代码,我的代码如下所示。
var AWS = require("aws-sdk");
var creds = new AWS.Credentials('akid', 'secret', 'session');
AWS.config.update({
"accessKeyId": "myAccessId",
"secretAccessKey": "MySecretAccessKey",
"region": "us-east-1"
});
var dynamodb = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: "MyTable",
FilterExpression: "#target_state = :target_state",
ExpressionAttributeNames: {
"#target_state": "target_state"
},
ExpressionAttributeValues: {
":target_state": "5"
}
};
var array = [];
dynamodb.scan(params).promise().then(function (data) {
data.Items.forEach(function (itemData) {
array.push(itemData.ruleNo)
});
console.log(array);
return array;
}).then(() => {
console.log("Entered 2nd block " + [...new Set(array)]);
var array2 = [...new Set(array)];
for (index = 0; index < array2.length; ++index) {
console.log(array2[index]);
var params1 = {
TableName: "ChemicalData",
FilterExpression: "#target_state = :target_state and #ruleNo=:ruleNo",
ExpressionAttributeNames: {
"#target_state": "target_state",
"#ruleNo": "ruleNo"
},
ExpressionAttributeValues: {
":target_state": "5",
":ruleNo": array2[index]
}
};
return dynamodb.scan(params1).promise().then(function (data) {
var uw = JSON.stringify((data.Items));
return uw;
});
}
}).then((data) => {
console.log(data);
}).catch(err => {
console.log(err)
})
当我运行这个程序时,我得到的结果只有一个值,这是第一个数组值,我无法知道如何遍历所有数组变量然后执行{ {1}}。请让我知道我哪里出错了,我该怎么办呢。
由于
答案 0 :(得分:1)
在里面使用return
打破循环。你应该从内部扫描收集承诺到数组,然后使用Promise.all
来解决这个问题
dynamodb.scan(params).promise().then(function (data) {
data.Items.forEach(function (itemData) {
array.push(itemData.ruleNo)
});
console.log(array);
return array;
}).then(() => {
console.log("Entered 2nd block " + [...new Set(array)]);
var array2 = [...new Set(array)];
var results = []; //results array
for (index = 0; index < array2.length; ++index) {
console.log(array2[index]);
var params1 = {
TableName: "ChemicalData",
FilterExpression: "#target_state = :target_state and #ruleNo=:ruleNo",
ExpressionAttributeNames: {
"#target_state": "target_state",
"#ruleNo": "ruleNo"
},
ExpressionAttributeValues: {
":target_state": "5",
":ruleNo": array2[index]
}
};
// push results to be resolved later
results.push(dynamodb.scan(params1).promise().then(function (data) {
var uw = JSON.stringify((data.Items));
return uw;
}));
}
// return promise that resolves when all results resolve
return Promise.all(results);
})