Get Value Back from AWS lambda.invoke synchronously

时间秒杀一切 提交于 2019-12-24 04:01:59

问题


I'm attempting to call an AWS Lambda function from another Lambda function using the invoke method with a RequestResponse invocation type and retrieve a value returned from the Lambda.

When I call the lambda.invoke using await the callback still appears to be called asynchronously. I'd like for the values I need to be available on the next line of code, hence the synchronous requirement. However, in the code below in the logs I see the "Data out of Callback" entry occur prior to the "Data in Callback" entry with a 0 value out of the callback and a correct value in the callback.

If anyone could help me understand how to accomplish this I would greatly appreciate it! Here's the code:

async readData() {

        let myData = [];

        const params = {
            FunctionName: "MyFunctionName",
            InvocationType: "RequestResponse",
        };

        await lambda.invoke(params, (error, data) => {
            if (error) {
                console.log("Got a lambda invoke error");
                console.error(error);
            } else {
                let response = JSON.parse(data.Payload);
                myData = JSON.parse(response.body);

                console.log("Data in Callback: " + myData.length);
            }
        });

        console.log("Data out of Callback: " + myData.length);
}

Thanks,

Chris


回答1:


AWS-SDK already promisified. If you want to use 8.10 runtime and try && catch block then simply use the following snippet:

    async readData() 
    {
        const params = 
        {
            FunctionName: "MyFunctionName",
            InvocationType: "RequestResponse",
        };

        try
        {
            const lambdaInvokeResp = await lambda.invoke(params).promise();

            // if succeed
            // handle your response here
            // example
            const lambdaRespParsed = JSON.parse(lambdaInvokeResp.Payload);
            const myData = JSON.parse(lambdaRespParsed.body);

            return myData;
        }
        catch (ex) // if failed
        {
            console.error(ex);
        }
    }



回答2:


Shortly after posting I finally stumbled across an answer to this, found in this post:

Invoke amazon lambda function from node app

Specifically the 3rd answer down, not the accepted solution.



来源:https://stackoverflow.com/questions/52630935/get-value-back-from-aws-lambda-invoke-synchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!