Skip to content
Advertisement

Nested async await function not executing in AWS Lambda Function

Problem: I have very little experience working with async await functions and I am trying to execute a nested async await function within an if-else statement that depends on a higher level async function to execute upon an event detection. I expect to get a successful http response back from the nested async function, but I continue getting a null value for a response. The nested async function works as expected outside of the if-else statement, however. My goal is to simply be able to get the “await new Promise” part of the code to return a http response within the conditional if-else statement. Any help with this is appreciated.

What I’ve tried: I haven’t really made any attempts to remedy the situation besides searching for questions with similar issues since I know very little about the nature of async await functions.

Code:

JavaScript

Expected result:

JavaScript

Actual result:

JavaScript

Advertisement

Answer

There are a few issues with your code:

  1. The nested async function — you’re creating it but never executing it
JavaScript

Two solutions:

JavaScript
  1. You can get rid of the nested async function by declaring the callback passed to forEach as async:
JavaScript
  1. The try/catch block at the end won’t catch any errors. Instead, wrap the Promise you created inside a try/catch block and reject from inside upon an error event:
JavaScript
  1. Running async operations inside forEach does not do what you intend to do. You probably intend to respond after all sensorsIds have been created. What really happens is that you respond as soon as the first sensorId is created. That’s because forEach fires the callbacks for data.Items simultaneously. A solution for this is to use map instead and return an array of Promises which you can then await with Promise.all.

Here’s the final code and how I would solve it. As an extra I’ve promisified ddb.scan so you’re not mixing callbacks with promises and async/await:

JavaScript

I hope you learned a thing or two from my response :). Let me know if you have any questions.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement