I'm toying with making something in node.js, and I (like everyone else who's ever started learning node) have a question about the asynchronous nature of it. I searched around a bit, but couldn't find this specific question about it answered (maybe I just didn't search very well...), so here goes:
Are node.js callbacks, in general, guaranteed to be asynchronous if the documentation says so? If you make your own functions that take callbacks, should you design in such a way so that they're either always asynchronous or always synchronous? Or can they be sometimes synchronous, sometimes not?
As an example, lets say you wanted to load some data over the internet, and you created a function to load it. But the data doesn't change very often, so you decide to cache it for future calls. You could imagine that someone would write that function something like this:
function getData(callback) {
if(dataIsCached) {
callback(cachedData)
} else {
fetchDataFromNetwork(function (fetchedData) {
dataIsCached = true;
cachedData = fetchedData;
callback(fetchedData);
});
}
}
Where fetchDataFromNetwork is a function that executes its callbacks asynchronously (this is slightly pseudo-codey, but I hope you understand what I mean).
This function will only fire asynchronously if the data isn't cached, if it is cached it just executes the callback directly. In that case, the asynchronous nature of the function is, after all, totally unnecessary.
Is this kind of thing discouraged? Should the second line of the function be setTimeout(function () {callback(cachedData)}), 0)
instead, to guarantee that it fires asynchronously?
The reason I'm asking is that I saw some code a while back where the code inside the callback simply assumed that the rest of the function outside the callback had executed before the code inside the callback. I recoiled a little at that, thinking "but how do you know that the callback will fire asynchronously? what if it doesn't need to and executes synchronously? why would you ever assume that every callback is guaranteed to be asynchronous?"
Any clarification on this point would be much appreciated. Thanks!