From 3a0f5bf8c8866793ffdc1c5762904f72b294d4f2 Mon Sep 17 00:00:00 2001 From: Stephen Paul Weber Date: Wed, 5 May 2021 09:21:09 -0500 Subject: [PATCH] Helper to allow using sync-style code in a Promise context 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. --- lib/em.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/lib/em.rb b/lib/em.rb index 9115641..d28a96b 100644 --- a/lib/em.rb +++ b/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 -- 2.38.5