首页 > 解决方案 > 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

标签: node.jsamazon-web-servicesaws-lambdaamazon-dynamodb

解决方案


问题是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 功能


推荐阅读