Class: Promise::When

Inherits:
Promise show all
Defined in:
lib/isomorfeus/promise.rb

Instance Attribute Summary

Attributes inherited from Promise

#error, #next, #prev

Instance Method Summary collapse

Methods inherited from Promise

#<<, #^, #act?, #action, #always, #always!, error, #exception!, #exception?, #fail, #fail!, #inspect, #pending?, #realized?, #reject, #reject!, #rejected?, #resolve, #resolve!, #resolved?, #then, #then!, #there_can_be_only_one!, #trace, #trace!, #value, value, when

Constructor Details

#initialize(promises = []) ⇒ When

Returns a new instance of When.



277
278
279
280
281
282
283
284
285
# File 'lib/isomorfeus/promise.rb', line 277

def initialize(promises = [])
  super()

  @wait = []

  promises.each {|promise|
    wait promise
  }
end

Instance Method Details

#>>Object



333
334
335
336
337
# File 'lib/isomorfeus/promise.rb', line 333

def >>(*)
  super.tap {
    try
  }
end

#collect(&block) ⇒ Object Also known as: map

Raises:

  • (ArgumentError)


295
296
297
298
299
300
301
# File 'lib/isomorfeus/promise.rb', line 295

def collect(&block)
  raise ArgumentError, 'no block given' unless block

  self.then {|values|
    When.new(values.map(&block))
  }
end

#each(&block) ⇒ Object

Raises:

  • (ArgumentError)


287
288
289
290
291
292
293
# File 'lib/isomorfeus/promise.rb', line 287

def each(&block)
  raise ArgumentError, 'no block given' unless block

  self.then {|values|
    values.each(&block)
  }
end

#inject(*args, &block) ⇒ Object Also known as: reduce



303
304
305
306
307
# File 'lib/isomorfeus/promise.rb', line 303

def inject(*args, &block)
  self.then {|values|
    values.reduce(*args, &block)
  }
end

#tryObject



339
340
341
342
343
344
345
346
347
# File 'lib/isomorfeus/promise.rb', line 339

def try
  if @wait.all?(&:realized?)
    if promise = @wait.find(&:rejected?)
      reject(promise.error)
    else
      resolve(@wait.map(&:value))
    end
  end
end

#wait(promise) ⇒ Object Also known as: and



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/isomorfeus/promise.rb', line 313

def wait(promise)
  unless Promise === promise
    promise = Promise.value(promise)
  end

  if promise.act?
    promise = promise.then
  end

  @wait << promise

  promise.always {
    try if @next.any?
  }

  self
end