I have a Serverless lambda function, in which I want to fire(invoke) a method and forget about it
I'm doing it with this way
// myFunction1
const params = {
FunctionName: "myLambdaPath-myFunction2",
InvocationType: "Event",
Payload: JSON.stringify(body),
};
console.log('invoking lambda function2'); // Able to log this line
lambda.invoke(params, function(err, data) {
if (err) {
console.error(err, err.stack);
} else {
console.log(data);
}
});
// my function2 handler
myFunction2 = (event) => {
console.log('does not come here') // Not able to log this line
}
I've noticed that until and unless I do a Promise
return
in myFunction1
, it does not trigger myFunction2
, but shouldn't set the lambda InvocationType = "Event"
mean we want this to be fire and forget and not care about the callback response?
Am I missing something here?
Any help is highly appreciated.
The first time you invoke your function, AWS Lambda creates an instance of the function and runs its handler method to process the event. When the function returns a response, it stays active and waits to process additional events.
When you invoke a function, you can choose to invoke it synchronously or asynchronously. With synchronous invocation, you wait for the function to process the event and return a response. With asynchronous invocation, Lambda queues the event for processing and returns a response immediately.
Synchronous Invocations The lambda would get a maximum of 30 seconds to run so the business logic had to complete within that time period. With that being said, most lambdas were still written to be completed within in a few 100s of milliseconds.
Your myFunction1
should be an async function that's why the function returns before myFunction2
could be invoked in lambda.invoke()
. Change the code to the following then it should work:
const params = {
FunctionName: "myLambdaPath-myFunction2",
InvocationType: "Event",
Payload: JSON.stringify(body),
};
console.log('invoking lambda function2'); // Able to log this line
return await lambda.invoke(params, function(err, data) {
if (err) {
console.error(err, err.stack);
} else {
console.log(data);
}
}).promise();
// my function2 handler
myFunction2 = async (event) => {
console.log('does not come here') // Not able to log this line
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With