-
Notifications
You must be signed in to change notification settings - Fork 0
/
control_node.rb
54 lines (43 loc) · 1008 Bytes
/
control_node.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class ControlNode
attr_reader :result, :state
def initialize
yield(method(:resolve), method(:reject))
end
def chain(on_success, on_failure=nil)
raise "ControlNode#chain requires a success branch" unless on_success
if @state == :succeeded
chain = on_success.call(result)
return chain.to_deferrable if chain.respond_to?(:to_deferrable)
ControlNode.new { |res,_| res.call(result) }
else
chain = on_failure.call(result) if on_failure
return chain.to_promise if chain.respond_to?(:to_promise)
VoidControlNode.new(result)
end
end
def to_promise
self
end
private
def resolve(val)
@state = :succeeded
@result = val
end
def reject(val)
@state = :failed
@result = val
end
class VoidNode
attr_reader :result, :state
def initialize(result)
@result = result
@state = :failed # implicitly
end
def to_promise
self
end
def chain(_,_=nil)
self
end
end
end