JavaScript is finicky. Finicky, I say!

As I continue to learn JavaScript in the context of Node.js and - now - Mongoose/MongoDB, I am starting to understand the harsh reality of the asynchronous environment.

You see, in Node.js (from here on out, just Node), as in JavaScript (from here on out, just JS), there is no multi-threading. As such, separate processes can’t run at the same time - technically speaking. In Node, every line is executed in the order in which it is called. Ok, great.

But JS is special in that you can pass functions as parameters to other functions. In that way, you can actually have two functions being executed at the same time. (Even though they were called consecutively!)

So, for example, let’s say function B is passed as a parameter to function A:

[js]function A ( function B () {} ) {}[/js]

Then function B is going to get started just after the rest of function A is executed.

A better (read: more understandable) example: Let’s say function A buys groceries. Function B makes the shopping list.

[js smarttabs=”true”]function buyGroceries( shoppingList ) {
// buy the items on the list
}

var shoppingList = function makeShoppingList( listItems ) {
// remember the chicken, pasta, and veggies
}[/js]

But! In order to buy groceries, you need to know what to buy, no? In a perfect world, the list would be made before you went to the store. Now let’s suppose you’re at the grocery store, but you don’t have the list. So you call your significant other (SO) to text you what you need for the pantry. In the meantime, you go into the store and start browsing around.

[js smarttabs=”true”]function buyGroceries(function makeShoppingList() {
// remember the chicken, pasta, and veggies!
}) {
pickUpItems();
goToCheckout();
purchaseItems();
}[/js]

But beware: If you leave before you get the message from your SO, then you can’t buy the groceries you need.

Or, in other words, if you close your connection to the database before your query finishes, then you won’t be getting the information you need in time.

You have been warned.