Class: Concurrent::Promise
- Inherits:
-
Object
- Object
- Concurrent::Promise
- Includes:
- Obligation, UsesGlobalThreadPool
- Defined in:
- lib/concurrent/promise.rb
Class Method Summary collapse
Instance Method Summary collapse
- #execute ⇒ Promise
-
#initialize(options = {}, &block) ⇒ Promise
constructor
A new instance of Promise.
- #on_success(&block) ⇒ Promise
- #rescue(&block) ⇒ Promise (also: #catch, #on_error)
-
#then(rescuer = nil, &block) ⇒ Promise
The new promise.
Methods included from UsesGlobalThreadPool
Methods included from Obligation
#completed?, #fulfilled?, #incomplete?, #pending?, #reason, #rejected?, #state, #unscheduled?, #value
Methods included from Dereferenceable
#init_mutex, #mutex, #set_deref_options, #value
Constructor Details
#initialize(options = {}, &block) ⇒ Promise
Returns a new instance of Promise.
14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/concurrent/promise.rb', line 14 def initialize( = {}, &block) .delete_if {|k, v| v.nil?} @parent = .fetch(:parent) { nil } @on_fulfill = .fetch(:on_fulfill) { Proc.new{ |result| result } } @on_reject = .fetch(:on_reject) { Proc.new{ |reason| raise reason } } @promise_body = block || Proc.new{|result| result } @state = :unscheduled @children = [] init_obligation end |
Class Method Details
.execute(&block) ⇒ Object
54 55 56 |
# File 'lib/concurrent/promise.rb', line 54 def self.execute(&block) new(&block).execute end |
Instance Method Details
#execute ⇒ Promise
41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/concurrent/promise.rb', line 41 def execute if root? if compare_and_set_state(:pending, :unscheduled) set_pending realize(@promise_body) end else @parent.execute end self end |
#on_success(&block) ⇒ Promise
76 77 78 79 |
# File 'lib/concurrent/promise.rb', line 76 def on_success(&block) raise ArgumentError.new('no block given') unless block_given? self.then &block end |
#rescue(&block) ⇒ Promise Also known as: catch, on_error
82 83 84 |
# File 'lib/concurrent/promise.rb', line 82 def rescue(&block) self.then(block) end |
#then(rescuer = nil, &block) ⇒ Promise
Returns the new promise.
60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/concurrent/promise.rb', line 60 def then(rescuer = nil, &block) raise ArgumentError.new('rescuers and block are both missing') if rescuer.nil? && !block_given? block = Proc.new{ |result| result } if block.nil? child = Promise.new(parent: self, on_fulfill: block, on_reject: rescuer) mutex.synchronize do child.state = :pending if @state == :pending child.on_fulfill((@value)) if @state == :fulfilled child.on_reject(@reason) if @state == :rejected @children << child end child end |