在AWS Lambda上调用功能异步 [英] Invoke function async on AWS Lambda
问题描述
我试图以异步方式调用函数,因为我不想等待响应.
I'm trying to invoke a function as async because I don't wan't to wait the response.
我已经阅读过AWS文档,并说将InvocationType
用作Event
,但只有在执行.promise()
时,它才有效.
I've read the AWS docs and there says to use InvocationType
as Event
but it only works if I do a .promise()
.
无效版本:
lambda.invoke({
FunctionName: 'rock-function',
InvocationType: 'Event',
Payload: JSON.stringify({
queryStringParameters: {
id: c.id,
template: c.csvTemplate
}
})
})
工作版本:
lambda.invoke({
FunctionName: 'rock-function',
InvocationType: 'Event',
Payload: JSON.stringify({
queryStringParameters: {
id: c.id,
template: c.csvTemplate
}
})
}).promise()
我能解释一下为什么会发生吗?
Anyone could me explain why it happens?
推荐答案
invoke
返回 send()
才将其发送.
invoke
returns an AWS.Request
instance, which is not automatically going to perform a request. It's a representation of a request which is not sent until send()
is invoked.
这就是为什么后一种版本有效但前一种版本无效的原因.调用.promise()
时发送请求.
That's why the latter version works but the former does not. The request is sent when .promise()
is invoked.
// a typical callback implementation might look like this
lambda.invoke({
FunctionName: 'rock-function',
InvocationType: 'Event',
Payload: JSON.stringify({
queryStringParameters: {
id: c.id,
template: c.csvTemplate,
},
}),
}, (err, data) => {
if (err) {
console.log(err, err.stack);
} else {
console.log(data);
}
});
// ... or you could process the promise() for the same result
lambda.invoke({
FunctionName: 'rock-function',
InvocationType: 'Event',
Payload: JSON.stringify({
queryStringParameters: {
id: c.id,
template: c.csvTemplate,
},
}),
}).promise().then(data => {
console.log(data);
}).catch(function (err) {
console.error(err);
});
这篇关于在AWS Lambda上调用功能异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!