Skip to content
Advertisement

JavaScript – Async/Await – How to Return result from nested functions?

I’m new to Node.js and having difficulty working with async/await model. The issue I’m having is with nested function calls returning data in an async/await method, I always get 'undefined'. My functions structure is like this:

JavaScript

I understand that if the top-level call is async/await then all the nested calls should be awaited as well that I’ve tried to do.

What am I doing wrong here?

Advertisement

Answer

Get rid of all the then, and also of the callback in the DB query. Use only await. It will make the whole code a lot easier to reason about and it should also solve your issue as part of the restructuring.

In the example below I also added a loop over the orders, because you are fetching all orders, as array, but then your code was behaving as if it got only one. I also fixed the products loop.

However, the way you fetch products doesn’t seem to be right anyway, see my comment below. I didn’t fix it because I don’t know how your database structure looks, so I don’t know what the right way would be.

JavaScript

Preemptive comment reply: The return await is intentional, and this is why.

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