Search code examples
node.jsamazon-web-servicesasynchronousaws-lambdaasynccallback

invoke aws lambda from another lambda asynchronously


I need to invoke aws lambda from another lambda asynchronously. i have a working code for synchronous calls.

exports.handler = (event, context, callback) => {
    var aws = require('aws-sdk');
    var lambda = new aws.Lambda({
        region: 'myregion' //change to your region
    });
    console.log("lambda invoke started");
    lambda.invoke({
        FunctionName: 'testLambda',
        Payload: JSON.stringify(event, null, 2) // pass params
    }, function (error, data) {
        if (error) {
            console.log("error");
            callback(null, 'hello world');
        }
        else {
            console.log("lambda invoke end");
            callback(null, 'hello world');
        }
    });
}

But in my case, 'testLambda' is a time taken function. Because i need to exit just after invoking the 'testLambda' function. Then code is updated like this

exports.handler = (event, context, callback) => {
    var aws = require('aws-sdk');
    var lambda = new aws.Lambda({
        region: 'myregion' //change to your region
    });
    console.log("lambda invoke started");
    lambda.invoke({
        FunctionName: 'testLambda',
        Payload: JSON.stringify(event, null, 2) // pass params
    });
    console.log("lambda invoke end");
    callback(null, 'hello world');
}

it returns message correctly . But my 'testLambda' function is not invoked(no cloud watch logs are generated for test lambda). what is the issue related with this code.


Solution

  • Per the Lambda invoke() documentation, you will see that by default the Lambda function is invoked using the RequestResponse invocation type. To invoke the function asynchronously you need to specify the Event invocation type, like so:

    lambda.invoke({
        FunctionName: 'testLambda',
        InvocationType: 'Event',
        Payload: JSON.stringify(event, null, 2)
    },function(err,data){});