Lothar
Lothar

Reputation: 3489

Handling multiple dependant queries in a nodejs function

I have a function that needs to query a database for items meeting a specific criteria then iterate over each item checking to see if it meets multiple further criteria and finally to take some action.

  1. First, get all books with a certain status
  2. Next, see if each book is checked out
  3. If it is checked out go see who has it, retrieve their email and send them a notice
  4. Regardless of checked out status send notices to the book manager and book owner
  5. Update the books status in the database

I started doing part of this in a non-async fashion and it actually worked. However, once I tried to determine if the book was checked out or not I ran into problems as that value was not retrieved before the function completed running. I tried using promises but found that they were still not getting the value back in time unless I stuck the rest of my code inside the then method but that led to needed values defined prior to the then not being available inside of it.

What is the best way to approach doing something like this? Something that needs to dynamically populate multiple values at run time from multiple database tables, but only under certain conditions and all while iterating over multiple records?

Upvotes: 0

Views: 258

Answers (1)

cybersam
cybersam

Reputation: 67044

Even synchronous processing can be implemented using an asynchronous functional style (that is, using callbacks to handle the result of some chunk of processing).

So, you should implement your new functionality using an asynchronous style.

I would also recommend going back and re-implementing the existing synchronous functions in an asynchronous style, as you may learn later that some processing may take longer than you expected (especially once your system starts growing).

Upvotes: 1

Related Questions