Class: Promise::When

Inherits:
Promise show all
Defined in:
opal/stdlib/promise.rb

Instance Attribute Summary

Attributes inherited from Promise

#error, #next, #prev, #value

Instance Method Summary collapse

Methods inherited from Promise

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

Constructor Details

#initialize(promises = []) ⇒ When

Returns a new instance of When



343
344
345
346
347
348
349
350
351
# File 'opal/stdlib/promise.rb', line 343

def initialize(promises = [])
  super()

  @wait = []

  promises.each {|promise|
    wait promise
  }
end

Instance Method Details

#>>Object



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

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

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

Raises:

  • (ArgumentError)


361
362
363
364
365
366
367
# File 'opal/stdlib/promise.rb', line 361

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

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

#each(&block) ⇒ Object

Raises:

  • (ArgumentError)


353
354
355
356
357
358
359
# File 'opal/stdlib/promise.rb', line 353

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



369
370
371
372
373
# File 'opal/stdlib/promise.rb', line 369

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

#tryObject



405
406
407
408
409
410
411
412
413
# File 'opal/stdlib/promise.rb', line 405

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



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'opal/stdlib/promise.rb', line 379

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
  }

  self
end