lib/volt/utils/promise_extensions.rb in volt-0.9.4.pre3 vs lib/volt/utils/promise_extensions.rb in volt-0.9.4.pre5
- old
+ new
@@ -1,11 +1,11 @@
# Require the original promise library first.
require 'volt/utils/promise'
# A temp patch for promises until https://github.com/opal/opal/pull/725 is released.
class Promise
-
+ class UnrealizedPromiseException < RuntimeError ; end
# We made a choice not to support comparitors and << and >> on method_missing
# on Promises. This makes it easier to understand what promise proxying does
# and how it works. It also prevents confusing situations where you try to
# == compare two Promises for example. The cost though is more code to do
# comparisons, but we feel it is worth it.
@@ -81,16 +81,29 @@
# Forward to resolved value
def to_json(*args, &block)
self.then {|v| v.to_json(*args, &block) }
end
+ # unwrap lets you return a value or raise an exceptoin on a realized promise.
+ # An exception will be raised if the promise is not realized yet.
+ def unwrap
+ if realized?
+ if resolved?
+ value
+ else
+ Object.send(:fail, error)
+ end
+ else
+ raise UnrealizedPromiseException, "#unwrap called on a promise that has yet to be realized."
+ end
+ end
-
- # Waits for the promise to resolve (assuming it is blocking on
- # the server) and returns the result.
+ # Waits for the promise to be realized (resolved or rejected), then returns
+ # the resolved value or raises the rejection error. .sync only works on
+ # the server (not in opal), and will raise a warning if on the client.
def sync
- raise ".sync can only be used on the client" if Volt.client?
+ raise ".sync can only be used on the server" if Volt.client?
result = nil
error = nil
self.then do |val|
@@ -101,10 +114,13 @@
if error
err_str = "Exception in Promise at .sync: #{error.inspect}"
err_str += error.backtrace.join("\n") if error.respond_to?(:backtrace)
Volt.logger.error(err_str)
- fail error
+
+ # The fail method in Promise is already defined, to re-raise the error,
+ # we send fail
+ Object.send(:fail, error)
else
return result
end
end
end