dynamoDB DocumentClient不等待循环内部-节点js 8.10

时间:2019-03-05 13:41:26

标签: node.js amazon-web-services aws-lambda amazon-dynamodb

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");

});
}

在控制台中,这将返回我:

matchID:3434

matchID:3543

在数据库中找到了3388 Hill U23团队

在数据库中找到了团队44108 Bridge U23

而不是:

matchID:3434

在数据库中找到了3388 Hill U23团队

matchID:3543

在数据库中找到了团队44108 Bridge U23

1 个答案:

答案 0 :(得分:1)

问题在于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函数