我遇到了 dynamoDB 无法在 for 循环中提供查询结果的问题。查询确实执行,但仅在循环完成后执行:
readMatchData(JSON) {
return new Promise((resolve, reject) => {
for (var jsonInfo of JSON.Feed.MatchData) {
var matchID = jsonInfo['@attributes'].matchID;
console.log("matchID: " + matchID);
var homeTeamID = team['@attributes'].homeTeamID;
var params = {
TableName: "Teams",
KeyConditionExpression: "#teamID = :teamID",
ExpressionAttributeNames: {
"#teamID": "teamID"
},
ExpressionAttributeValues: {
":teamID": homeTeamID
},
ReturnConsumedCapacity: "TOTAL"
}
docClient.query(params, function(err, data) {
if (err) {
//console.log("We have an error when looking for the team in the Teams table");
console.log(err);
} else {
if (data.Count === 0) {
//We did not find this ID in the db so we can add it.
console.log("The team doesn't exist");
} else {
data.Items.forEach(function(item) {
console.log("Team " + item.teamID + " " + item.teamName + " found in the database");
})
}
}
});
}
resolve("done");
});
}
在控制台中,这将返回我:
比赛ID:3434
比赛ID:3543
数据库中找到 3388 Hill U23 队
在数据库中找到Team 44108 Bridge U23
而不是:
比赛ID:3434
数据库中找到 3388 Hill U23 队
比赛ID:3543
在数据库中找到Team 44108 Bridge U23
最佳答案
问题是 docClient
调用使用回调,如以下行所示:
docClient.query(params, function(err, data) { ... })
这意味着在操作完成之前(可能会晚一些时间)才会调用您传递的函数。
您可以告诉库将其包装在 promise 中,然后等待它:
const data = await docClient.query(params).promise()
if (data.Count === 0) {
//We did not find this ID in the db so we can add it.
console.log('The team doesn\'t exist')
} else {
data.Items.forEach(function (item) {
console.log('Team ' + item.teamID + ' ' + item.teamName + ' found in the database')
})
}
编辑:目前您正在将整个函数包装在一个 promise 中,但由于我们将其隔离为回调,您可能希望将其替换为看起来更像:
async function readMatchData () {
for (var jsonInfo of JSON.Feed.MatchData) {
var matchID = jsonInfo['@attributes'].matchID
console.log('matchID: ' + matchID)
var homeTeamID = team['@attributes'].homeTeamID
var params = {
TableName: 'Teams',
KeyConditionExpression: '#teamID = :teamID',
ExpressionAttributeNames: {
'#teamID': 'teamID'
},
ExpressionAttributeValues: {
':teamID': homeTeamID
},
ReturnConsumedCapacity: 'TOTAL'
}
const data = await docClient.query(params).promise()
if (data.Count === 0) {
//We did not find this ID in the db so we can add it.
console.log('The team doesn\'t exist')
} else {
data.Items.forEach(function (item) {
console.log('Team ' + item.teamID + ' ' + item.teamName + ' found in the database')
})
}
}
return 'done'
}
编辑:感谢 HMilbradt 指出该库有一个内置的 promisify 函数
关于node.js - dynamoDB DocumentClient 不在循环内等待 - Node js 8.10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55004241/