繁体   English   中英

coffeescript承诺链接功能定义

[英]coffeescript promise chaining with function definition

当承诺在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

但是,这并没有多大意义,因为你在函数中没有引用this 你可能想实际上只是通过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

要么:

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

如果你的函数只是单行,那么匿名函数就可以了,但如果它们更长,那么很容易迷失在CoffeeScript的空白中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM