Helper to allow using sync-style code in a Promise context

Stephen Paul Weber created

This helper spins up a fiber and returns an unresolved EMPromise, then runs the
passed-in block inside the fiber and fulfills the promise with the result of the
block. Because nothing is looking for the Fiber to return it is free to act as a
trampoline for EMPromise#sync and other fiber-sync-style code that does not
block the EM reactor.

Change summary

lib/em.rb | 12 ++++++++++++
1 file changed, 12 insertions(+)

Detailed changes

lib/em.rb 🔗

@@ -12,4 +12,16 @@ module EM
 		)
 		promise
 	end
+
+	def self.promise_fiber
+		promise = EMPromise.new
+		Fiber.new {
+			begin
+				promise.fulfill(yield)
+			rescue StandardError => e
+				promise.reject(e)
+			end
+		}.resume
+		promise
+	end
 end