为什么AWS-SDK-Javascript v3 API call to DynamoDB 返回undefined并且没有按期望打印console.log的内容

0

【以下的问题经过翻译处理】 这段代码的目的是为了获取聊天室的所有连接id,以便在API Gateway WebSocket中回复发送消息的命令。我经常使用PutCommand和GetCommand,但今天我第一次使用QueryCommand。代码第一部分是DynamoDB调用部分。

代码片段1:

export async function ddbGetAllRoomConnections(room) {
  const params = {
        "TableName": "MessageTable",
        "KeyConditionExpression": "#DDB_room = :pkey",
        "ExpressionAttributeValues": {
          ":pkey": ""
        },
        "ExpressionAttributeNames": {
          "#DDB_room": "room"
        },
        "ScanIndexForward": true,
        "Limit": 100
  };
  console.log("ddbGetAllRoomConnections-1:",params);
  const data = await ddbClient.send( new QueryCommand(params) );
  console.log("ddbGetAllRoomConnections-2:",data);
  return data;
}


调用部分:

const normalConnections = ddbGetAllRoomConnections(connData.lastroom);
            if (typeof normalConnections.Items === 'undefined' || normalConnections.Items.length <= 0) {
              throw new Error("Other Connections not found");
            }


下面是按顺序整理过的日志信息:

logfile puzzle message1:
ddbGetAllRoomConnections-1: {
  TableName: 'MessageTable',
  KeyConditionExpression: '#DDB_room = :pkey',
  ExpressionAttributeValues: { ':pkey': '' },
  ExpressionAttributeNames: { '#DDB_room': 'room' },
  ScanIndexForward: true,
  Limit: 100
}

logfile puzzle message2:
ERROR   Error: Other Connections not found
    at Runtime.handler (file:///var/task/chat-messages.js:49:21)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  statusCode: 500
}

logfile puzzle message3:
END RequestId: 

让我困扰的是,日志文件中出现的以下序列:

  1. ddbGetAllRoomConnections-1: 日志出现在命令 ddbClient.send 调用之后, 这个我认为是正确的
  2. ddbGetAllRoomConnections-2 log 没有如预期出现在ddbClient.send 之后
  3. 接下来ddbGetAllRoomConnections的调用出现了undefined错误.
1 回答
0

【以下的回答经过翻译处理】 请使用await:

const normalConnections = ddbGetAllRoomConnections(connData.lastroom);

应该改为:

const normalConnections = await ddbGetAllRoomConnections(connData.lastroom);

你的代码是有效的,但normalConnections将是一个Promise而不是结果。

profile picture
专家
已回答 8 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则