简体   繁体   中英

Response from AWS lambda function called from another lambda function is always null

I have two lambda functions and I need to call a function named sendHealthData from a function named receiveHealthData . I'm using Node.JS 8.10 and the Serverless framework.

Here's the code to receiveHealthData :

const env = process.env;
const aws = require("aws-sdk");
const Lambda = new aws.Lambda();
const S3 = new aws.S3();

exports.main = (event, context, callback) => {

    const params = {
        FunctionName: "sendHealthData",
        InvocationType: "RequestResponse",
        Payload: JSON.stringify(event)
    }

    Lambda.invoke(params, function(error, remainingHealthData) {

        if (error) {

            reject(error);
        }
        else {

            console.log("Remaining: " + remainingHealthData["Payload"]);

            if (!remainingHealthData["Payload"]) {

                reject(new Error("Payload is null"));
            }  
            else {

                resolve(remainingHealthData);
            }
        }
    });
}

And this is sendHealthData :

exports.main = async (event, context, callback) => {

    callback(null, "Sent Health Data!");
}

remainingHealthData["Payload"] is null everytime.

The output of console.log(JSON.stringify(remainingHealthData)) is:

{"StatusCode":200,"Payload":'null'}

When I invoke sendHealthData through serverless invoke --function sendHealthData I get the expected result: "Sent Health Data!"

I got the expected response only once: when I changed the timeout of the sendHealthData function. But the strange thing is that I changed it to a smaller value. It was 10 and I changed it to 6.

The issue is that you are using RequestResponse as InvocationType but your sendHealthData AWS Lambda doesn't return a valid JSON (just a string).

A small quote out of the documentation says:

Payload — (Buffer, Typed Array, Blob, String)

It is the JSON representation of the object returned by the Lambda function. This is present only if the invocation type is RequestResponse.

So as soon as you change the return value of your sendHealthData AWS Lambda to the following it should work as you expect:

exports.main = async (event, context, callback) => {
  callback(null, {
    "message": "Sent Health Data!"
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM