Class: EventMachine::Q::DeferredPromise
- 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
-
#initialize(defer) ⇒ DeferredPromise
constructor
A new instance of DeferredPromise.
-
#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.
Constructor Details
#initialize(defer) ⇒ DeferredPromise
Returns a new instance of DeferredPromise.
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.
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.}\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.}\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 |