I always do it like this:
f = -> deferred = Q.defer() FS.readFile ..., ( error, text ) -> return deferred.reject error if error? deferred.resolve text return deferred.promise
The first return should stop execution, and not return a value.
you still get an extra (and meaningless) return in your JS from the last line of the callback; to avoid this, add an extra return null (or just return if you want to).
I'm not sure I like the implicit insertion in CoffeeScript; it can be argued that "explicit is better than implicit." In addition, it can be argued that the first return should not be return , but with another keyword, for example, stop or finish or somesuch.
as an unrelated side element, I did not notice any noticeable benefits when using promises. on the contrary, I found them rather intrusive in my code that with these deferred and other concepts that are put on top of asynchronous programming.
flow Jul 21 '14 at 10:27 2014-07-21 10:27
source share