Sha256: 5060c67bdabf8c42c3b92321bcfebdd32d4871536cdeb08ba351c219daeb3a74

Contents?: true

Size: 1.14 KB

Versions: 3

Compression:

Stored size: 1.14 KB

Contents

##
# Meta-programming String for Syntactic Sugars
# Referenced from {Qiita}[http://qiita.com/south37/items/99a60345b22ef395d424]
class Promise
  # Init a Promise
  # @param [Proc] callback an async method
  def initialize(&callback)
    @callback = callback
  end

  # Define what to do after a method callbacks
  # @param [Proc] resolve what on callback
  # @return [nil] nil
  def then(&resolve)
    @callback.call(resolve)
  end
end

module Kernel
  def async_fiber(fiber)
    chain = proc do |result|
      next unless result.is_a? Promise
      result.then do |val|
        chain.call(fiber.resume(val))
      end
    end
    chain.call(fiber.resume)
  end

  # Define an async method
  # @param [Symbol] method method name
  # @yield async method
  # @example
  #   async :hello do 
  #     puts 'Hello'
  #   end
  def async(method)
    define_singleton_method method do |*args|
      async_fiber(Fiber.new {yield(*args)})
    end
  end

  # Block the I/O to wait for async method response
  # @param [Promise] promise promise method
  # @example
  #   result = await SQL.query('SELECT * FROM hello')
  def await(promise)
    Fiber.yield promise
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
em-midori-0.1.12 lib/midori/core_ext/promise.rb
em-midori-0.1.11 lib/midori/core_ext/promise.rb
em-midori-0.1.10 lib/midori/core_ext/promise.rb