为什么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 Antwort
0

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

const normalConnections = ddbGetAllRoomConnections(connData.lastroom);

应该改为:

const normalConnections = await ddbGetAllRoomConnections(connData.lastroom);

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

profile picture
EXPERTE
beantwortet vor 8 Monaten

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen