我的lambda函数在第一次调用后超时。第一次调用它是成功的,但当您调用它时,它会一直超时。一旦超时,它就会再次工作。我假设是因为lambda已经重新启动了。axios是否存在内存泄漏,这就是它超时的原因?
const users = require('./services/users');
let response;
exports.lambdaHandler = async (event) => {
try {
const result = await users.saveData('Smith', 'John')
const response = {
'isBase64Encoded': true | false,
'statusCode': 200,
'body': JSON.stringify(result)
};
return response;
} catch (error) {
return {
'isBase64Encoded': true | false,
'statusCode': 200,
'body': JSON.stringify(
{'message': 'error msg'}
);
}
}
};
下面是我的用户模块:
const axios = require('axios')
const FormData = require('form-data');
const data = new FormData();
exports.saveData = async (lastName, firstName) => {
try {
data.append('lastName', lastName);
data.append('firstName', firstName);
} catch (error) {
throw Error(error);
}
const url = 'https://sample.com/users';
const config = {
method: 'post',
url,
data: data
};
try {
const result = await axios(config);
return result;
} catch (error) {
throw new Error('An Error Occurred');
}
}
一个常见的问题是,默认情况下,在完成执行之前,等待事件循环为空。看见https://dev.to/dvddpl/event-loops-and-idle-connections-why-is-my-lambda-not-returning-and-then-timing-out-2oo7
因此,请尝试从以下位置更改代码:
exports.lambdaHandler = async (event) => {
try {
收件人:
exports.lambdaHandler = async (event, context) => {
context.callbackWaitsForEmptyEventLoop = false;
try {
这样,即使事件循环不是空的,Lambda也会完成代码的执行。