javascript - 带有函数定义的 coffeescript promise 链接

标签 javascript coffeescript q

当在 coffeescript 中进行 promise 链接时,为 then 定义的函数需要绑定(bind)到“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);
  })));

最佳答案

使用=>而不是自己绑定(bind)它,它会更容易阅读并且是正确的。

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

但是,这实际上没有意义,因为您没有在函数中引用 this。实际上,您可能只想将 dosomething 直接传递给 then(),因此保留了它的 ThisBinding

关于javascript - 带有函数定义的 coffeescript promise 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27595933/

相关文章:

php - 两个循环 JS 函数相互冲突

javascript - CoffeeScript : if . 。是..那么

node.js - Node : child_process. exec() 进程在父进程死亡后继续

javascript - 如何在 Promise.spread 内部和外部使用 Q Promise 的结果

javascript - 如何使用 Q.js 正确链接条件(?) promise

javascript - 将 div 缩放为像背景图像一样的 div

javascript - 使用 Flask 表单发送额外数据?

javascript - 为什么要重用XmlHttpRequest对象?

javascript - 无法访问 Requirejs 模块内的另一个类

javascript - 避免类似协程的 JavaScript 函数中的 "yield"重复