问题
I'm trying to invoke a function as async because I don't wan't to wait the response.
I've read the AWS docs and there says to use InvocationType
as Event
but it only works if I do a .promise()
.
not working version:
lambda.invoke({
FunctionName: 'rock-function',
InvocationType: 'Event',
Payload: JSON.stringify({
queryStringParameters: {
id: c.id,
template: c.csvTemplate
}
})
})
working version:
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?
回答1:
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.
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);
});
来源:https://stackoverflow.com/questions/54768574/invoke-function-async-on-aws-lambda