Class: Promise::When

Inherits:
Promise show all
Defined in:
opal/stdlib/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, #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.



373
374
375
376
377
378
379
380
381
# File 'opal/stdlib/promise.rb', line 373

def initialize(promises = [])
  super()

  @wait = []

  promises.each do |promise|
    wait promise
  end
end

Instance Method Details

#>>Object



429
430
431
432
433
# File 'opal/stdlib/promise.rb', line 429

def >>(*)
  super.tap do
    try
  end
end

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

Raises:

  • (ArgumentError)


391
392
393
394
395
396
397
# File 'opal/stdlib/promise.rb', line 391

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

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

#each(&block) ⇒ Object

Raises:

  • (ArgumentError)


383
384
385
386
387
388
389
# File 'opal/stdlib/promise.rb', line 383

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

  self.then do |values|
    values.each(&block)
  end
end

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



399
400
401
402
403
# File 'opal/stdlib/promise.rb', line 399

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

#tryObject



435
436
437
438
439
440
441
442
443
444
# File 'opal/stdlib/promise.rb', line 435

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

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



409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# File 'opal/stdlib/promise.rb', line 409

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

  if promise.act?
    promise = promise.then
  end

  @wait << promise

  promise.always do
    try if @next.any?
  end

  self
end