Javascript 带有函数定义的coffeescript承诺链接

Javascript 带有函数定义的coffeescript承诺链接,javascript,coffeescript,q,Javascript,Coffeescript,Q,在coffeescript中进行承诺链接时,为定义的函数需要绑定到“this” $q.fcall somecall .then ((url)-> dosomething() ).bind(this) .catch (err)-> console.log 'error occured', err 但是,上面的内容编译成了下面的内容,这是错误的。那么如何正确书写呢?或者有没有一种方法可以让coffeescript来表示这一点 $q.fcall(s

在coffeescript中进行承诺链接时,为定义的函数需要绑定到“this”

  $q.fcall somecall
  .then ((url)->
    dosomething()
    ).bind(this)
  .catch (err)->
    console.log 'error occured', err
但是,上面的内容编译成了下面的内容,这是错误的。那么如何正确书写呢?或者有没有一种方法可以让coffeescript来表示这一点

  $q.fcall(somecall).then(((function(url) {
    dosomething()
  }).bind(this))["catch"](function(err) {
    return console.log('error occured', err);
  })));
使用而不是自己装订,它会更容易阅读和正确

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

然而,这并没有真正的意义,因为您在函数中没有提到
这个
。您可能想直接将
dosomething
传递到
then()
,这样它的
ThisBinding
就被保留了。

仅仅因为您可以使用匿名函数并不意味着您必须这样做。给出回调名称通常会导致代码更清晰:

some_descriptive_name = (url) ->
  dosomething()
the_error = (err) ->
  console.log 'error occurred', err

$q.fcall somecall
  .then some_descriptive_name.bind(@)
  .catch the_error
或:


如果您的函数只是一行程序,那么匿名函数也可以,但如果它们较长,则很容易在CoffeeScript的空白中迷失方向。

这确实有帮助。但是编译之后,生成的javascript代码仍然显示
[“catch”](函数(err){return console.log('error is',err);})@WeideZhang:怎么了
o.m()
o['m']()
是等价的,因此CoffeeScript使用字符串形式。
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