5 ms·
I would point out that there are cases where sync callbacks do make sense (granted, this does not look like one of them). 1. You want to add optional results.
by morganherlocker 13y ago
I would point out that there are cases where sync callbacks do make sense (granted, this does not look like one of them).
1. You want to add optional results. See underscore's each function that returns an object for the current iteration, then an optional iterator value in addition, which you sometimes need.
2. There are many functional patterns that utilize callbacks where you want to pass functions in as parameters (which could do anything, including accessing the file system or waiting on an external call). Underscore also has loads of examples where this is the case, despite being a sync library.
3. This is probably the least valid reason, but sometimes you do not know going in whether or not a function you are writing will be async. If you create a sync interface, it will need to be changed if the function needs to be async in the future, or if it needs to pass additional results. In my experience the latter is not terribly uncommon. The former is pretty unlikely in library code, but I could see it happening in application code regularly. Breaking apis is not fun for anyone.
- quarterto 13y agoCallbacks ≠ passing functions as arguments. Callbacks (in the node sense) is passing a single function as the final argument which will be called exactly once with an error or result. The function passed to _.each is used to access the elements of an array. It is called once for each element. It is used as a mechanism to pass a block of code to _.each, not to get a result from _.each.