Sha256: e2757c15228505dd477be42946229d5446b40cde3d1b61ccf8a3584796d2e355

Contents?: true

Size: 1.04 KB

Versions: 5

Compression:

Stored size: 1.04 KB

Contents

# encoding: utf-8

class Promise
  class Callback
    def initialize(block, next_promise)
      @block = block
      @next_promise = next_promise
    end

    private

    def execute(value)
      @block.call(value)
    rescue => error
      @next_promise.reject(error)
      raise
    end

    def handle_result(result)
      if Promise === result
        assume_state(result)
      else
        @next_promise.fulfill(result)
      end
    end

    def assume_state(returned_promise)
      on_fulfill = @next_promise.method(:fulfill)
      on_reject = @next_promise.method(:reject)

      returned_promise.then(on_fulfill, on_reject)
    end
  end

  class FulfillCallback < Callback
    def dispatch(value)
      if @block
        result = execute(value)
        handle_result(result)
      else
        handle_result(value)
      end
    end
  end

  class RejectCallback < Callback
    def dispatch(reason)
      if @block
        result = execute(reason)
        handle_result(result)
      else
        @next_promise.reject(reason)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
promise.rb-0.5.0 lib/promise/callback.rb
promise.rb-0.4.0 lib/promise/callback.rb
promise.rb-0.3.0 lib/promise/callback.rb
promise.rb-0.2.1 lib/promise/callback.rb
promise.rb-0.2.0 lib/promise/callback.rb