Sam Barnum
Sam Barnum

Reputation: 10714

Coffeescript converts try / catch / finally block oddly when a function reference is used

I have a helper function for dealing with errors. I'm trying to pass this as a parameter to the catch function in a promise:

  fetchRecords().then (found) ->
    $scope.recprds = found;
  .catch( Session.handleError )
  .finally( -> $scope.querying = false )

This gets parsed into the following Javascript:

  fetchRecords().then(function(found) {
    return $scope.records = found;
  })["catch"](Session.handleError)["finally"](function() {
    return $scope.querying = false;
  });

Which cases a JavaScript error because finally is not a property of my Session.handleError function.

Is there a different syntax I should be using?

Try it out on coffeescript.org

Upvotes: 2

Views: 1105

Answers (1)

apxp
apxp

Reputation: 5884

First: you should delete the ; and the ( ) where they are not needed.

The words try catch and finally are reserved words. You should use them like the example at the coffeescript.org page:

try
  allHellBreaksLoose()
  catsAndDogsLivingTogether()
catch error
  print error
finally
  cleanUp()

If you change your function names the chaining in coffeescript is working. So you should rename your helper functions and the chaining should work.

  fetchRecords().then (found) ->
    $scope.recprds = found
  .helpercatch Session.handleError 
  .helperfinally -> $scope.querying = false 

Parses:

fetchRecords().then(function(found) {
  return $scope.recprds = found;
}).helpercatch(Session.handleError).helperfinally(function() {
  return $scope.querying = false;
});

Upvotes: 2

Related Questions