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() 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
for ... ofloop instead.forEachdoesn’t await async functions, and nothing else in your code is either.forEachto afor ... ofand madecheckServerasync, but it didn't resolve the issue unfortunately, the values after theawaitline still seem to get skipped. Even ifforEachdoesn't await async functions, that shouldn't prevent "x" orres(even if it'sundefined) from printing, right?let res = await axios(apiToTest)probably throws an exception. As you are not catching it, code execution is aborted .