如何在Lambda函数中调用Lambda函数?
例如,
在功能1 中,它将由API网关请求触发,并将调用第二个lambda函数作为事件(InvocationType = Event)。
在功能2 中,它将向端点发出http请求。
另外,我要在serverless.yml中编码吗?或仅在index / app / handler.js上进行编码?
我在stackoverflow上尝试了链接-> Nodejs - Invoke an AWS.Lambda function from within another lambda function,但是它不起作用。
var AWS = require('aws-sdk');
AWS.config.region = 'eu-west-1';
var lambda = new AWS.Lambda();
//LAMBDA A
exports.handler = function(event, context) {
var params = {
FunctionName: 'Lambda_B', // the lambda function we are going to invoke
InvocationType: 'RequestResponse',
LogType: 'Tail',
Payload: '{ "name" : "Yza" }'
};
lambda.invoke(params, function(err, data) {
if (err) {
context.fail(err);
} else {
context.succeed('Lambda_B said '+ data.Payload);
}
})
};
//LAMBDA B
exports.handler = function(event, context) {
console.log('Lambda B Received event:', JSON.stringify(event, null, 2));
context.succeed('Hello ' + event.name);
};
答案 0 :(得分:0)
您的问题是lambda.invoke()
函数是非阻塞的,因此Lambda_A在调用Lambda_B之前已完成其执行。您可以使用诺言来处理。如果您是using Node.js 8.10+,则可以执行以下操作:
Lambda_A:
let AWS = require('aws-sdk');
let lambda = new AWS.Lambda();
exports.handler = async (event) => {
let params = {
FunctionName: 'Lambda_B',
InvocationType: 'RequestResponse',
Payload: '{ "foo" : "bar" }'
};
return await lambda.invoke(params, function(err, data) {
if (err) {
throw err;
} else {
console.log('LambdaB invoked: ' + data.Payload);
}
}).promise();
};
Lambda_B:
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify('Hello from Lambda_B!'),
};
};
调用Lambda_A时的响应:
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST",
"Payload": "{\"statusCode\":200,\"body\":\"\\\"Hello from Lambda_B!\\\"\"}"
}
从Lambda_A调用控制台输出:
START RequestId: 016a763d-c79e-4d72-bd44-0aaa89a5efaf Version: $LATEST
2019-02-07T08:07:11.154Z 016a763d-c79e-4d72-bd44-0aaa89a5efaf LambdaB invoked: {"statusCode":200,"body":"\"Hello from Lambda_B!\""}
END RequestId: 016a763d-c79e-4d72-bd44-0aaa89a5efaf
REPORT RequestId: 016a763d-c79e-4d72-bd44-0aaa89a5efaf Duration: 717.40 ms Billed Duration: 800 ms Memory Size: 128 MB Max Memory Used: 30 MB
答案 1 :(得分:0)
您可以添加一个用户,该用户的策略包括LambdaInvoke,然后添加以下配置
bla_bla