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

Viewed 1439

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.

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
 }
Related