从另一个Lambda调用AWS Lambda,子Lambda立即停止



是的,我看过许多帖子和stackoverflow关于如何从另一个lambda异步调用lambda的答案。我可以从父函数调用子函数。但是不知道为什么我的子lambda函数在100ms内立即关闭,看起来像我的子lambda与我的父lambda同步工作。

这是我的父lambda具有HttpAPI类型网关:

// PARENT LAMBDA having HttpAPI gateway.
const AWS = require("aws-sdk");
const auth = require("./services/auth");
var Lambda = new AWS.Lambda();
/**
* Note: Step Functions, which are called out in many answers online, do NOT actually work in this case. The reason
* being that if you use Sequential or even Parallel steps they both require everything to complete before a response
* is sent. That means that this one will execute quickly but Step Functions will still wait on the other one to
* complete, thus defeating the purpose.
*
* @param {Object} event The Event from Lambda
*/
// LAMBDA A
exports.handler = async (event, context, callback) => {
user = auth.authenticateUser(event);
const userId = auth.authenticateUser(event);
if (!user) {
return auth.UNAUTHORISED;
}
let params = {
FunctionName: "my-child-lambda-here",
InvocationType: "Event", // <--- This is KEY as it tells Lambda to start execution but immediately return / not wait.
Payload: JSON.stringify(event),
};
// we have to wait for it to at least be submitted. Otherwise Lambda runs too fast and will return before
// the Lambda can be submitted to the backend queue for execution
// LAMBDA B
await new Promise((resolve, reject) => {
Lambda.invoke(params, function (err, data) {
if (err) {
reject(err, err.stack);
} else {
console.log(data);
resolve("Lambda invoked: " + data);
}
});
});
// Always return 200 not matter what
return {
statusCode: 200,
body: "Your request is currently being processed",
};
};

这是我的子lambda:

// CHILD LAMBDA!!
exports.handler = async (event) => {
console.log("inside child Lambda!!!!!!!!!!!")
console.log(event)
let i = 0;
// repeat with the interval of 1 seconds
let timerId = setInterval(() => console.log("count: ", i++), 1000);
console.log("inside child Lambda print 2!!!!!!!!!!!")
setTimeout(() => console.log("setTimoutTesting"), 10);
// after 15 seconds stop
setTimeout(() => { clearInterval(timerId); console.log("stop"); }, 15000);
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};

我的yaml有以下iam设置允许另一个lambda调用:

provider:
name: aws
memorySize: 128
runtime: nodejs14.x
lambdaHashingVersion: 20201221
region: us-east-2
iam:
role:
name: invoke-other-lambda-role
statements:
- Effect: 'Allow'
# Resource: '*'
Resource: 'arn:aws:lambda:*:*:function:*'
Action:
- 'lambda:InvokeAsync'
- 'lambda:InvokeFunction'

我不是node.js方面的专家,但据我所知,lambda处理程序实际上并不等到setTimeout()完成。如果您真的想等待超时发生,您应该将其转换为Promise对象,并在同一函数中对其执行await。在这里可以找到一个很好的例子(代码片段应该是不言自明的):https://stackoverflow.com/a/42183439/12259756.

我的问题是,为什么你首先要这样做,因为与其他技术相比,lambda在这种等待15秒的用例中是非常昂贵的服务。在逻辑中包含等待的一种便宜的方法是例如阶跃函数。

最新更新