Callbacks in Node.js
Callbacks can often be visually confusing and hard to conceptualize; however, fundamentally, they are quite simple. A callback is a function provided as a parameter to a second function, which allows both functions to be run in order.
Without using callbacks (or any other synchronization pattern), both functions would start executing right after the other. When using a driver, this would create errors, because the second function may be dependent on the first function finishing before it begins. For example, you cannot query your data until the connection is established. Let's look at a breakdown of a callback:
Figure 8.4: Breakdown of a callback
And now, compare this to our find
query code:
Figure 8.5: Breakdown of a MongoDB callback
As you can see, the same structure exists, just with different parameters to the callback function. You may be wondering how we know which parameters to use in a specific callback...