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

Posted

技术标签:

【中文标题】AWS.ApiGatewayManagementApi.postToConnection() 调用一次时执行两次【英文标题】:AWS.ApiGatewayManagementApi.postToConnection() executes twice when called once 【发布时间】:2021-04-16 07:32:13 【问题描述】:

我正在编写一个 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: 

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

【问题讨论】:

【参考方案1】:

显然是因为我同时使用了回调和承诺。

删除回调,如下所示:

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() 部分,但我宁愿不这样做;与回调相比,promise 是一种更简洁、更现代的解决方案。

【讨论】:

以上是关于AWS.ApiGatewayManagementApi.postToConnection() 调用一次时执行两次的主要内容,如果未能解决你的问题,请参考以下文章