|
|
|
|
|
by samstokes
5070 days ago
|
|
I did the same thing in Ruby [1], but it does indeed look uglier than the equivalent Haskell/Scala because of the lack of language support for monadic syntax. The benefit of realising the monadic behaviour of asynchronous sequencing (which I call "Deferrable#bind!") was that if you had a bunch of nested callbacks, the monad associativity law [2] meant you could replace them with a simple linear sequence of chained bind! calls: fetch().bind! do |a|
process(a)
end.bind! do |b|
process(b)
end.bind! do |c|
# ...
end
instead of fetch().callback do |a|
process(a).callback do |b|
process(b).callback do |c|
# ...
end
end
end
I find the former a lot more readable, partly because the "end" keywords don't all pile up at the end, and especially if you try and do error handling (in the nested case the error handling ends up in reverse order!).[1] https://github.com/samstokes/deferrable_gratification#bind-f... [2] http://www.haskell.org/haskellwiki/Monad_Laws |
|