Sal*_*Sal 8 amazon-web-services node.js async-await aws-lambda
I'm trying to use AWS lambda to test a few API calls using axios, however I'm having some trouble. Every post I came across said the best way to handle promises in Lambda was to use async/await rather than .then, so I made the switch. When I run the program using node it works perfectly, but when I invoke the Lambda locally, it seems like everything after the axios call is being skipped. When I invoke the Lambda locally without await, the calls after it run fine, but then I'm forced to use .then which the Lambda doesn't wait for anyway. I've increased the Lambda timeout to 900, and I've run sam build before sam invoke local every time.
function checkServers() {
console.log("Inside checkServer");
console.log("Before apis to test");
// apisToTest has length of 2
apisToTest.forEach(async (apiToTest) => {
console.log("Api to test");
let res = await axios(apiToTest)
console.log("x"); // This gets skipped
console.log(res); // This gets skipped
})
console.log("After api to test")
}
exports.lambdaHandler = async (event, context) => {
console.log("Inside lambda handler");
checkServers();
console.log("After lambda handler");
};
// Used to test app using node command
checkServers()
Run Code Online (Sandbox Code Playgroud)
This yields the following output:
INFO Inside lambda handler
INFO Inside checkServer
INFO Before apis to test
INFO Api to test
INFO Api to test
INFO After api to test
INFO After lambda handler
Run Code Online (Sandbox Code Playgroud)
感谢您的所有回复,不幸的是,这些并不是我的用例的理想解决方案,尽管它们对我提出解决方案非常有帮助。
async function checkServers() {
let emailBody = "";
let callResult = "";
let completedCalls = 0;
let promises = [];
for (const apiToTest of apisToTest) {
await axios(apiToTest).then((res) => {
// Do something
}).catch((r) => {
// Handle error
})
}
}
exports.lambdaHandler = async (event, context) => {
context.callbackWaitsForEmptyEventLoop = true;
await checkServers();
};
Run Code Online (Sandbox Code Playgroud)
总而言之,我将调用替换forEach为调用for...of,将 更改checkServers为async,并结合await和.then()来.catch处理Promise结果。我不知道两者可以同时使用。希望这对遇到与我类似问题的人有所帮助。
| 归档时间: |
|
| 查看次数: |
6010 次 |
| 最近记录: |