In my code below, 5 always prints before 4. I thought because the callback to postUsers
was in a return statement from matchAgainstAD
it would wait
ad.findUser
takes a callback that contains the console.log(4)
. That function is async, and will hit your callback when the IO operation has completed.
On the other hand, postUsers
is called completely synchronously, so it will hit console.log(5)
before ad.findUser
enters your callback.
A simple way to fix this is to call postUsers
from inside of your ad.findUser
callback.
I would suggest looking into the promise pattern for JavaScript to manage dependencies between async operations. There are several popular libraries (Q and RSVSP.js being a couple of them).