I have seen three ways to return a JSON object or end a Lambda function. My trigger is Smart Home Alexa.
I am using now is
context.succeed(response_JSON);This one works for me. Even if this instructions is inside a nested function. The whole Lambda ends and return the response_JSON to Smart Home Alexa.I have seen in other blogs that say
callback(response_error,response_JSON). This one did not work for me. It did not return anything to Smart Home.Others just uses the
return response_JSON. I have not used this one.
context.succeed()/fail()causes the Lambda function to terminate immediately. However, I have not seen this documented in the context object docs, so it may get deprecated in later Node versions (?).This one probably doesn't work for you because by default Node.js waits for the event loop to be empty before executing the
callbackstatement. This may be due to open network/database connection. As per the doc, set thecontext.callbackWaitsForEmptyEventLoopvariable to false to send the response right away.This should be used with async handlers. Read more about async and non-async handlers here: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html