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);
})));
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.
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.
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