当在 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/