lib/dharma/promise_actions.rb in dharma-0.9.0 vs lib/dharma/promise_actions.rb in dharma-0.9.1

- old
+ new

@@ -45,11 +45,22 @@ def recover(cb = nil, &block) cb ||= block p = Dharma.promise - on_complete { |value| p.complete(cb.call(value)) } + on_complete do |value, as| + case as + when :failure + begin + p.complete(cb.call(value)) + rescue => e + p.failure(e) + end + when :success + p.success(value) + end + end p end def recover_with(cb = nil, &block) @@ -62,11 +73,73 @@ begin p.complete_with(cb.call(value)) rescue => e p.failure(e) end - else + when :success p.complete(value) + end + end + + p + end + + def map(cb = nil, &block) + cb ||= block + p = Dharma.promise + + on_complete do |value, as| + begin + case as + when :success + p.success(cb.call(value)) + when :failure + p.failure(value) + end + rescue => e + p.failure(e) + end + end + + p + end + + def flat_map(cb = nil, &block) + cb ||= block + p = Dharma.promise + + on_complete do |value, as| + begin + case as + when :success + cb.call(value).on_complete do |value2, as2| + case as2 + when :success + p.success(value2) + when :failure + p.failure(value2) + end + end + when :failure + p.failure(value) + end + rescue => e + p.failure(e) + end + end + + p + end + + def failed + p = Dharma.promise + + on_complete do |value, as| + case as + when :failure + p.success(value) + when :success + p.failure(NoSuchElementException.new("Future.failed not completed with an exception.")) end end p end \ No newline at end of file