AWS.ApiGatewayManagementApi.postToConnection() 调用一次执行两次

AWS.ApiGatewayManagementApi.postToConnection() executes twice when called once

我正在编写一个 Lambda 函数,当消息发送到我的 WebSocket API 时调用该函数,现在我只是试图将该消息回显给发件人。

exports.handler = async (event) => {
    const route = event.requestContext.routeKey;
    const connectionId = event.requestContext.connectionId;
        
    switch (route) {
        case '$connect':
            console.log('A client connected:', connectionId);
            break;
        case '$disconnect':
            console.log('A client disconnected:', connectionId);
            break;
        case 'command':
            const body = JSON.parse(event.body);
            const command = body.command;
            console.log('Received a command:', command);
            try {
                await echoCommand(command, connectionId);
            } catch (err) {
                console.log("Encountered an error when echoing:", err);
            }
            break;
    }
    
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

async function echoCommand(command, connectionId) {
    console.log("Inside echo now...");
    const responseData = { command };
    const postParams = {
        ConnectionId: connectionId,
        Data: Buffer.from(JSON.stringify(responseData))
    };
    
    return api.postToConnection(postParams, (err, data) => {
        if (!err)
            console.log("Successfully echoed the command. Data:", data);
        else
            console.log("Encountered an unknown error:", err);
    }).promise();
}

问题是,即使 echoCommand(...) 被调用一次,postToConnection(...) 也会执行两次。

日志(删除不必要的文本后):

INFO A client connected: d3YK_d77joECEYg=
INFO Received a command: commandToSend
INFO Inside echo now...
INFO Successfully echoed the command. Data: {}
INFO Successfully echoed the command. Data: {}

为什么会发生这种情况,我该如何解决?

看来是因为我同时使用了回调和promise

移除回调,像这样:

async function echoCommand(command, connectionId) {
    console.log("Inside echo now...");
    const responseData = { command };
    const postParams = {
        ConnectionId: connectionId,
        Data: Buffer.from(JSON.stringify(responseData))
    };
    
    return api.postToConnection(postParams).promise();
}

或者,.promise() 部分可以删除,但我宁愿不删除; promises 是比回调更简洁、更现代的解决方案。