Coffeescript whole chain with function definition

When a chain is promised in coffeescript, the function defined for this should be bound to 'this'.

$q.fcall somecall .then ((url)-> dosomething() ).bind(this) .catch (err)-> console.log 'error occured', err 

However, the above compiles to the following, which is incorrect. How to write? Or is there a way for coffeescript to represent this?

  $q.fcall(somecall).then(((function(url) { dosomething() }).bind(this))["catch"](function(err) { return console.log('error occured', err); }))); 
+5
source share
2 answers

Use => instead of binding it yourself, it will read much easier and be correct.

 $q.fcall somecall .then (url) => dosomething() .catch (err)-> console.log 'error occured', err 

However, this does not make sense since you are not referencing this in your function. You might want to just pass dosomething directly to then() , so its ThisBinding saved.

+3
source

Just because you can use anonymous functions does not mean what you need. Casting callback names often leads to clearer code:

 some_descriptive_name = (url) -> dosomething() the_error = (err) -> console.log 'error occurred', err $q.fcall somecall .then some_descriptive_name.bind(@) .catch the_error 

Or:

 some_descriptive_name = (url) => # fat-arrow instead of bind dosomething() the_error = (err) -> console.log 'error occurred', err $q.fcall somecall .then some_descriptive_name .catch the_error 

If your functions are only single-line, then anonymous functions are fine, but if they are longer, then it is very easy to get lost in CoffeeScript spaces.

+1
source

Source: https://habr.com/ru/post/1209678/


All Articles