static static - 4 months ago 13
CoffeeScript Question

How to avoid an implicit "return" in coffeescript in conditional expressions?

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?

Answer

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)