CoffeeScript 承诺与函数定义链接

coffeescript promise chaining with function definition

本文关键字:定义 链接 函数 承诺 CoffeeScript      更新时间:2023-09-26

当在咖啡脚本中做承诺链接时,定义的函数需要绑定到"this"。

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

但是,以上编译成以下内容,这是错误的。那么如何正确书写呢?或者有没有办法让咖啡脚本来表示这一点?

  $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 的空白中。