I am implementing a function that has deferred value to return and within the function I have many nested conditional expressions:
e.g.:
deferred = Q.defer()
FS.readFile("foo.txt", "utf-8", (error, text) ->
if error
deferred.reject(new Error(error))
else
deferred.resolve(text)
)
return deferred.promise
which than will be compiled into:
var deferred;
deferred = Q.defer();
FS.readFile("foo.txt", "utf-8", function(error, text) {
if (error) {
--> return <-- deferred.reject(new Error(error));
} else {
--> return <-- deferred.resolve(text);
}
});
return deferred.promise;
I need only the last return, but not the if/else returns (i.e. --> return <-- in the compiled code)
How can I avoid such a behavior (implicit returns where they are do not needed) of the coffeescript compiler?
What is Implicit Return? A function is returned values without using the return keyword, it's called an implicit return. The Rules of Implicit Return. You must use an implicit return in a concise body.
As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).
Coffeescript automatically returns the result of the last expressions, so if you don't want it to return the results of the if
then you need to add another expressions. In this case, just add return
.
FS.readFile "foo.txt", "utf-8", (error, text) ->
if error
deferred.reject new Error(error)
else
deferred.resolve text
return
Also, error
is already an Error
object, so you can just reject it directly.
deferred.reject(error)
You can't, exactly. You can either ignore them when not needed (which is the most common thing to do) or provide an explicit alternative by adding an additional statement at the end of the function. I think trying to do this all the time in your code base is fighting a war against the language you cannot win, so my personal recommendation is just accept Mr. Ashkenas's implicit return and go on your merry way.
fs.readFile "foo.txt", "utf-8", (error, text) ->
# postfix style if statement here avoids the else
# of course, the value returned you may not like, so
# you probably won't use this style, but my boilerplate for
# error handling is
# return callback(error) if error
return deferred.reject(new Error(error)) if error
deferred.resolve(text)
# Here you can add an explicit return like
return
# or some other expression
null
# or 'this' in cases where chainability might be nice
this
# or so you don't accidentally delete this statement later thinking it is
# useless
return null
any of those forms will work, but in practice I don't see these commonly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With