Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serverless: Fire and forget by invoke method does not work as expected

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.

like image 830
Manzur Khan Avatar asked Oct 09 '19 06:10

Manzur Khan


People also ask

What happens when you invoke your Lambda for the first time and the Lambda function returns a response?

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.

What happens when Lambda is invoked?

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.

How long does it take to invoke a Lambda function?

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.


1 Answers

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
 }
like image 50
Surendhar E Avatar answered Jan 05 '23 01:01

Surendhar E