4 ms·
The author says that as a rule of thumb, he uses callbacks for every function, synchronous or not. wat. When you design an asynchronous function, you're tellin
by nickporter 12y ago
The author says that as a rule of thumb, he uses callbacks for every function, synchronous or not. wat.
When you design an asynchronous function, you're telling your caller that he can go and do other stuff (e.g. process other requests) while you're fetching his result in the background. Async functions should never block. If making everything async was a good idea, then underscore would be async.
The author also mentions that it is node convention to use callbacks. Sure, that's true. But he's calling his callbacks the wrong way. Node convention is `callback(error, result)`, not `callback(result)`.
Oh and promises ftw.
Articles like this hurt JavaScript's credibility, and certainly doesn't help new JS/node devs.
- santoriv 12y agoI agree. Using a synchronous programming style (i.e. function returns value) whenever you are performing a synchronous operation is always going to be more clear than using an asynchronous programming style for synchronous operations (i.e. function invokes passed function with value and returns undefined). And that's why many languages have await - to help make the async code have a more synchronous(and more easily readable) programming style.
- shawnz 12y agoI agree that it is a bit overzealous to say that every function should return its data using callbacks, but sometimes it makes sense even for synchronous functions. By making a function which doesn't accept a callback, you are creating an API that can never be made asynchronous, which could cause you more work in the long run. For example, consider a function with a synchronous implementation. It gets the data from a place that is quick and easy to access, so making it async is not necessary. But later on, that data gets moved to an external database. Now, in the best case, every place where that function is used must be updated to be made asynchronous. In the worst case, every caller of the function, as well as every caller of those functions, and so on, must be updated. And quite often, converting synchronous code to async is no small feat.
- nickporter 12y agoI knew someone would say that, hah! I am 100% for making sync functions asynchronous if it's implementation might have to be async in the future. In fact, I have done so many times for the exact example you have mentioned.