Class: Promise

Inherits:
RubyPromises::CleanObject show all
Defined in:
lib/ruby-promises.rb

Defined Under Namespace

Classes: ThenEnv

Instance Method Summary collapse

Constructor Details

#initializePromise

Returns a new instance of Promise.



22
23
24
25
# File 'lib/ruby-promises.rb', line 22

def initialize
  @success_chain = []
  @error_chain = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



47
48
49
# File 'lib/ruby-promises.rb', line 47

def method_missing method, *args
  result.send method, *args
end

Instance Method Details

#resolve(arg = nil) ⇒ Object



41
42
43
44
45
# File 'lib/ruby-promises.rb', line 41

def resolve arg = nil
  _rescue 'can\'t call result twice!' if @started
  @started = true
  _apply arg
end

#then(success = nil, error = nil, &blk) ⇒ Object

Raises:

  • (ArgumentError)


27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/ruby-promises.rb', line 27

def then success = nil, error = nil, &blk
  if blk
    if success.nil?
      success = blk
    elsif error.nil?
      error = blk
    end
  end
  raise ArgumentError.new('the first arg should be callable') unless success.respond_to?(:call)
  raise ArgumentError.new('the second arg should be callable') unless !error || error.respond_to?(:call)
  @success_chain << [success, error]
  self
end