链接承诺在咖啡 [英] Chaining Promises in Coffeescript
问题描述
有没有办法在Coffeescript中链接 Promises
。例如,考虑以下JavaScript代码,
Is there a way to chain Promises
together in Coffeescript. For example, consider the following javascript code,
return $.getJSON('/api/post.json')
.then(function(response) {
// do something
})
.then(function(response) {
// do something
})
.then(null, function(err) {
// do something
});
每个然后是
最后的然后
需要由函数返回。
目前我在coffeescript写这个,
Each of the then's
is optional, and the final then
needs to be returned by the function.
Currently I am writing this in coffeescript as,
promise = $.getJSON('/api/post.json')
promise = promise.then (response) ->
// do something
promise = promise.then (response) ->
// do something
promise = promise.then null, (err) ->
// do something
return promise
更好的办法做到这一点?谢谢。
Is there a better way to do this? Thanks.
推荐答案
Ezekiel显示正确的方法,但它不需要函数周围的括号。只要做:
Ezekiel shows the right way, but it doesn't need the parentheses around the functions. Just do:
$.getJSON '/api/post.json' # As of CoffeeScript 1.7, you don't need the parentheses here either.
.then (response) ->
# do something
response # if you would not return anything, promise would be fulfilled with undefined
.then (response) ->
# do something
undefined # necessary to prevent empty function body
.then null, (err) ->
# handle error
我觉得很奇怪。
当你需要同时添加onRejected和onFulfilled处理程序时,比较混乱的一件事。
I think it's surprisingly clean. The one thing that's relatively messy is when you need to add onRejected and onFulfilled handlers at the same time.
注意:我上次检查时,工作在CoffeeScript Redux,但是这是几个月前。
Note: Last time I checked, this did not work in CoffeeScript Redux, but this was a few months ago.
注意2:在每个函数中至少需要一行实际代码(即不只是一个注释)身体为这工作。通常情况下,你会的,所以这不是一个大问题。
Note 2: You need at least one line of actual code (i.e. not just a comment) in each function body for this to work. Typically, you will, so it's not a big issue.
这篇关于链接承诺在咖啡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!