Class: Promise
- Inherits:
-
Object
- Object
- Promise
- Defined in:
- lib/promise.rb,
lib/promise/version.rb
Constant Summary collapse
- VERSION =
"0.0.1"
Instance Attribute Summary collapse
-
#reason ⇒ Object
readonly
Returns the value of attribute reason.
-
#state ⇒ Object
readonly
Returns the value of attribute state.
-
#value ⇒ Object
readonly
Returns the value of attribute value.
Instance Method Summary collapse
-
#initialize(&block) ⇒ Promise
constructor
A new instance of Promise.
- #then(on_fulfilled = nil, on_rejected = nil) ⇒ Object
Constructor Details
#initialize(&block) ⇒ Promise
Returns a new instance of Promise.
7 8 9 10 11 12 13 14 |
# File 'lib/promise.rb', line 7 def initialize(&block) @state = :pending @value = nil @reason = nil @callbacks = [] @errbacks = [] instance_eval(&block) if block_given? end |
Instance Attribute Details
#reason ⇒ Object (readonly)
Returns the value of attribute reason.
5 6 7 |
# File 'lib/promise.rb', line 5 def reason @reason end |
#state ⇒ Object (readonly)
Returns the value of attribute state.
5 6 7 |
# File 'lib/promise.rb', line 5 def state @state end |
#value ⇒ Object (readonly)
Returns the value of attribute value.
5 6 7 |
# File 'lib/promise.rb', line 5 def value @value end |
Instance Method Details
#then(on_fulfilled = nil, on_rejected = nil) ⇒ Object
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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/promise.rb', line 20 def then(on_fulfilled = nil, on_rejected = nil) result = Promise.new call_and_fulfill = ->(value) { begin if function?(on_fulfilled) new_value = on_fulfilled.call(value) if Promise === new_value new_value.then(->(v) { result.fulfill(v) }, ->(r) { result.reject(r) }) else result.fulfill(new_value) end else result.fulfill(value) end rescue Exception => e result.reject(e) end } call_and_reject = ->(reason) { begin if function?(on_rejected) new_value = on_rejected.call(reason) if Promise === new_value new_value.then(->(v) { result.fulfill(v) }, ->(r) { result.reject(r) }) else result.fulfill(new_value) end else result.reject(reason) end rescue Exception => e result.reject(e) end } case @state when :pending @callbacks << call_and_fulfill @errbacks << call_and_reject when :fulfilled call_and_fulfill.call(@value) when :rejected call_and_reject.call(@reason) end result end |