Is there a way to invoke AWS Lambda synchronously from node.js?

wagshadow picture wagshadow · Jan 17, 2018 · Viewed 7.2k times · Source

I'm trying to run a specific function from an existing app via AWS Lambda, using the JS SDK to invoke Lambda from my node.js app. Since I'm overwriting the existing function, I'll have to keep its basic structure, which is this:

overwrittenFunction = function(params) {
    //get some data
    return dataArray;
}

..so I need to end up with an array that I can return, if I'm looking to keep the underlying structure of the lib I use the same. Now as far as I know, Lambda invocations are asynchronous, and it's therefore not possible to do something like this:

overwrittenFunction = function(params) {
    lambda.invoke(params, callback);
    function callback(err,data) {
        var dataArray = data;
    }
    return dataArray;
}

(I've also tried similar things with promises and async/await).

afaik I have two options now: somehow figure out how to do a synchronous Lambda invocation, or modify my library / existing app (which I would rather not do if possible).

Is there any way to do such a thing and somehow return the value I'm expecting?

(I'm using node v8.9.4)

Answer

slaughtr picture slaughtr · Jun 20, 2018

Lambda and async/await are a bit tricky, but the following is working for me (in production):

const lambdaParams = {
    FunctionName: 'my-lambda',
    // RequestResponse is important here. Without it we won't get the result Payload
    InvocationType: 'RequestResponse',
    LogType: 'Tail', // other option is 'None'
    Payload: {
        something: 'anything'
    }
};

// Lambda expects the Payload to be stringified JSON
lambdaParams.Payload = JSON.stringify(lambdaParams.Payload);

const lambdaResult = await lambda.invoke(lambdaParams).promise();

logger.debug('Lambda completed, result: ', lambdaResult.Payload);

const resultObject = JSON.parse(lambdaResult.Payload)

Wrap it all up in a try/catch and go to town.