Sha256: 65c27d4a89ed519d6fc5b7b0ea55ee17942c2198129626ff27cbd16015dff78c

Contents?: true

Size: 1.03 KB

Versions: 1

Compression:

Stored size: 1.03 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)
    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

1 entries across 1 versions & 1 rubygems

Version Path
promise.rb-0.1.0 lib/promise/callback.rb