~singpolyma/em_promise.rb

ref: a91c67edf393000f2e2d2358a7cc3c07016d3b75 em_promise.rb/lib/em_promise.rb -rw-r--r-- 1.2 KiB
a91c67edStephen Paul Weber Allow users to catch only some errors 2 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
61
62
63
64
65
66
67
68
69
70
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 catch_only(*klasses, filter: ->(*) { false })
		catch do |e|
			if klasses.find { |klass| e.is_a?(klass) } || filter[e]
				yield e
			else
				EMPromise.reject(e)
			end
		end
	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