无服务器:通过调用方法的“Fire and forget”不如预期运行

9
我有一个无服务器(Serverless)的lambda函数,我想要调用(invoke)一个方法并且不再关注它。
我是通过以下方式实现的:
   // 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
  }

我注意到在myFunction1中,除非我执行Promise return,否则不会触发myFunction2。但是,设置lambda的InvocationType="Event"难道不应该意味着我们希望这是一个启动即忘记(fire and forget)的操作,并不关心回调响应吗?

我有什么遗漏吗?

任何帮助都将不胜感激。


你是否检查了Cloudwatch中的日志,以确定调用失败的原因? - Surendhar E
1个回答

2

您的myFunction1应该是一个异步函数,这就是为什么在lambda.invoke()中调用myFunction2之前函数返回的原因。将代码更改为以下内容,然后它应该可以工作:

 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
 }

如果您使用.promise,那么就不需要回调函数了吗? - backdesk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接