~singpolyma/em_promise.rb

ref: 3eb8964beef18fea6d7257a9aa231be811154953 em_promise.rb/lib/em_promise.rb -rw-r--r-- 996 bytes
3eb8964bStephen Paul Weber Initial commit 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
require "eventmachine"
require "promise"

class EMPromise < Promise
	def initialize(deferrable=nil)
		super()
		fulfill(deferrable) if deferrable
	end

	def fulfill(value, bind_defer=true)
		if bind_defer && value.is_a?(EM::Deferrable)
			value.callback { |x| fulfill(x, false) }
			value.errback(&method(:reject))
		else
			super(value)
		end
	end

	def defer
		EM.next_tick { yield }
	end

	def wait
		fiber = Fiber.current
		resume = proc do |arg|
			defer { fiber.resume(arg) }
		end

		self.then(resume, resume)
		Fiber.yield
	end

	def self.reject(e)
		new.tap { |promise| promise.reject(e) }
	end

	def self.all(enumerable)
		super(enumerable.map { |input|
			if input.respond_to?(:promise)
				input.promise
			else
				input
			end
		})
	end
end

module EventMachine
	module Deferrable
		def promise
			EMPromise.new(self)
		end

		[:then, :rescue, :catch].each do |method|
			define_method(method) do |*args, &block|
				promise.public_send(method, *args, &block)
			end
		end
	end
end