在 Coffeescript 中链接 Promise [英] 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
});
每个then的
都是可选的,最后的then
需要函数返回.目前我在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.
这篇关于在 Coffeescript 中链接 Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!