Class: EventMachine::Q::DeferredPromise

Inherits:
Promise
  • Object
show all
Defined in:
lib/em-promise/q.rb

Overview

A new promise instance is created when a deferred instance is created and can be retrieved by calling deferred.promise

Instance Method Summary collapse

Constructor Details

#initialize(defer) ⇒ DeferredPromise

Returns a new instance of DeferredPromise.

Raises:

  • (ArgumentError)


23
24
25
26
27
28
# File 'lib/em-promise/q.rb', line 23

def initialize(defer)
	raise ArgumentError unless defer.is_a?(Deferred)
	super()
	
	@defer = defer
end

Instance Method Details

#then(callback = nil, errback = nil, &blk) ⇒ Promise

regardless of when the promise was or will be resolved / rejected, calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument, the result or rejection reason.

Parameters:

  • callbacks (Proc, Proc, &blk)

    success, error, success_block

Returns:

  • (Promise)

    Returns an unresolved promise for chaining



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
71
72
73
74
75
# File 'lib/em-promise/q.rb', line 37

def then(callback = nil, errback = nil, &blk)
	result = Q.defer
	
	callback ||= blk
	
	wrappedCallback = proc { |val|
		begin
			result.resolve(callback.nil? ? val : callback.call(val))
		rescue => e
			warn "\nUnhandled exception: #{e.message}\n#{e.backtrace.join("\n")}\n"
			result.reject(e);
		end
	}
	
	wrappedErrback = proc { |reason|
		begin
			result.resolve(errback.nil? ? Q.reject(reason) : errback.call(reason))
		rescue => e
			warn "Unhandled exception: #{e.message}\n#{e.backtrace.join("\n")}\n"
			result.reject(e);
		end
	}
	
	#
	# Schedule as we are touching shared state
	#	Everything else is locally scoped
	#
	EM.schedule do
		pending_array = pending
		
		if pending_array.nil?
			value.then(wrappedCallback, wrappedErrback)
		else
			pending_array << [wrappedCallback, wrappedErrback]
		end
	end
	
	result.promise
end