How to invoke an AWS Lambda function from within another lambda function with Node.js?

Sometimes, we want to invoke an AWS Lambda function from within another lambda function with Node.js.

In this article, we’ll look at how to invoke an AWS Lambda function from within another lambda function with Node.js.

How to invoke an AWS Lambda function from within another lambda function with Node.js?

To invoke an AWS Lambda function from within another lambda function with Node.js, we can call the lambda.invoke method.

For instance, we write

const AWS = require('aws-sdk');
AWS.config.region = 'eu-west-1';
const lambda = new AWS.Lambda();

exports.handler = (event, context) => {
  const params = {
    FunctionName: 'LambdaB',
    InvocationType: 'RequestResponse',
    LogType: 'Tail',
    Payload: '{ "name" : "Jane" }'
  };

  lambda.invoke(params, (err, data) => {
    if (err) {
      context.fail(err);
    } else {
      context.succeed('Lambda_B said ' + data.Payload);
    }
  })
}

in the first lambda to define a unction that calls lambda.invoke with the params object.

In params, we specify the name of the Lambda function to run with FunctionName.

And we set the Payload that we pass to 'LambdaB'.

Then in LambdaB, we listen for invocations with

exports.handler = (event, context) => {
  context.succeed(event.name);
};

And get the Payload value from event.

Conclusion

To invoke an AWS Lambda function from within another lambda function with Node.js, we can call the lambda.invoke method.