Class: Celluloid::Promise::Coordinator
- Inherits:
-
Object
- Object
- Celluloid::Promise::Coordinator
- Includes:
- Celluloid
- Defined in:
- lib/celluloid-promise/q.rb
Instance Method Summary collapse
-
#all(*promises) ⇒ Promise
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
-
#defer(reactor = nil) ⇒ Deferred
Creates a Deferred object which represents a task which will finish in the future.
-
#initialize ⇒ Coordinator
constructor
A new instance of Coordinator.
-
#reject(reason = nil) ⇒ Promise
Creates a promise that is resolved as rejected with the specified reason.
Constructor Details
#initialize ⇒ Coordinator
Returns a new instance of Coordinator.
213 214 215 216 217 218 219 |
# File 'lib/celluloid-promise/q.rb', line 213 def initialize @reactors = [] @current = -1 # So we pick 0 first threads = ::Celluloid.cores threads += 1 if threads == 1 threads.times { @reactors << Reactor.new_link } # Have a thread for each core and link promises to each thread for serialisation end |
Instance Method Details
#all(*promises) ⇒ Promise
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
# File 'lib/celluloid-promise/q.rb', line 278 def all(*promises) reactor = next_reactor deferred = Deferred.new(reactor) counter = promises.length results = [] if counter > 0 promises.each_index do |index| ref(promises[index], reactor).then(proc {|result| if results[index].nil? results[index] = result counter -= 1 deferred.resolve(results) if counter <= 0 end result }, proc {|reason| if results[index].nil? deferred.reject(reason) end reason }) end else deferred.resolve(results) end return deferred.promise end |
#defer(reactor = nil) ⇒ Deferred
Creates a Deferred object which represents a task which will finish in the future.
226 227 228 |
# File 'lib/celluloid-promise/q.rb', line 226 def defer(reactor = nil) return Deferred.new(next_reactor(reactor)) end |
#reject(reason = nil) ⇒ Promise
Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don’t need to worry about it.
When comparing deferreds/promises to the familiar behaviour of try/catch/throw, think of reject as the raise keyword in Ruby. This also means that if you “catch” an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to “rethrow” the error by returning a rejection constructed via reject.
264 265 266 |
# File 'lib/celluloid-promise/q.rb', line 264 def reject(reason = nil) return ResolvedPromise.new(next_reactor, reason, true) # A resolved failed promise end |