node.js - dynamoDB DocumentClient 不在循环内等待 - Node js 8.10

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

});
}

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

比赛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/

相关文章:

javascript - Node.js 中的对象内存存储

node.js - 在 react-native 中上传 blob/文件,内容为空

macos - 使用Jenkins : command not found?运行AWS命令行界面

node.js - 使用 aws nodejs sdk 发送电子邮件(使用 aws sdk nodejs 文档)

node.js - 在 nodejs 中使用 FilterExpression 进行 DynamoDB 扫描

javascript - 安装 jsdom - Node js 时出现 MS 错误

javascript - 将数组元素写入不同的文件

javascript - 实用程序.crypto.lib。 randomBytes 不是函数 : aws cognito js throws error on authentication

amazon-web-services - 使用 AWS Lambda 响应正文映射 AWS API Gateway 中的多个 http 响应 header

dependency-injection - Dagger 与 Java AWS Lambda?