Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

coffeescript promise chaining with function definition

When do promise chaining in coffeescript, function defined for then need to bind to 'this'.

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

However, the above compiles into following,which is wrong. How to write correctly then ? 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);
  })));
like image 448
Weide Zhang Avatar asked Sep 30 '22 03:09

Weide Zhang


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, that doesn't really make sense as you don't refer to this in your function. You might want to actually just pass dosomething directly to then(), so its ThisBinding is preserved.

like image 170
alex Avatar answered Oct 01 '22 18:10

alex


Just because you can use anonymous functions doesn't mean you have to. Giving your callbacks 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 just one-liners then anonymous functions are fine but if they're longer, it is very easy to get lost in CoffeeScript's whitespace.

like image 32
mu is too short Avatar answered Oct 01 '22 20:10

mu is too short