node.js - dynamoDB DocumentClient 不在循环内部等待 - 节点 js 8.10
问题描述
我在使用 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");
});
}
在控制台中,这返回了我:
比赛编号:3434
比赛编号:3543
在数据库中找到 Team 3388 Hill U23 Team
在数据库中找到 Team 44108 Bridge U23
而不是:
比赛编号:3434
在数据库中找到 Team 3388 Hill U23 Team
比赛编号: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')
})
}
编辑:目前您将整个函数包装在一个承诺中,但由于我们将其隔离为仅回调,您可能希望将其替换为看起来更像:
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 功能
推荐阅读
- ios - 如何在代码中删除xib的视图约束?
- r - R - 仅提取特定行后的第一个数字
- web - 使用 PIXI JS 捕获屏幕截图时导致此问题的原因
- javascript - Javascript 中的异步编程 - Promise.all() 无法按预期工作
- macos - 如何在 Mac 上通过 chrome 和 firefox 保存 SSL 证书?
- reactjs - 根据道具动态选择文件
- python - Raspberry Pi Flask Server 关机后无法访问
- python - 更新购物车中的商品数量无法正常工作
- linux - gunicorn.service 的单元文件、源配置文件或插件在磁盘上已更改。运行“systemctl daemon-reload”重新加载单元
- java - Wildfly 查询字符串包含 // 用单斜杠 (/) 替换其中 servlet 使用发送重定向(302 代码)