title: Waiting for async calls with EventMachine and Ruby fibers
body: <p>I'm running this code snippet under Ruby 1.9.2:</p>
  
  <pre><code>require "eventmachine"
  require "fiber"
  
  EM.run do
    fiber = Fiber.new do
      current_fiber = Fiber.current
      EM.add_timer(2) do
        print "B"
        current_fiber.resume("D")
      end
      Fiber.yield
    end
    print "A"
    val = fiber.resume
    print "C"
    print val
    EM.stop
  end
  </code></pre>
  
  <p>I'm expecting the output to be "ABCD", with the program pausing for two seconds after the "A". However, instead it just prints out "AC" right away, then waits around for two seconds before exiting. What am I doing wrong?</p>
  
  <p>(For reference, I'm trying to reproduce the em-synchrony-style behaviour described in <a href="http://www.igvita.com/2010/03/22/untangling-evented-code-with-ruby-fibers/">this article</a> without using em-synchrony.)</p>
  
  <p>Edit: Here are some more details about what I'm ultimately trying to accomplish. I'm developing a Grape API running on Thin, and each route handler has to make various calls in series to datastores, ZooKeeper, other HTTP services, etc. before returning a response.</p>
  
  <p>em-synchrony is really cool, but I keep running into issues with yielding from the root fiber or with results showing the non-synchronous symptoms of the case above. rack-fiber_pool also seems potentially useful, but I'm reluctant to commit to using it because, out of the box, it breaks all my Rack::Test unit tests.</p>
  
  <p>I reduced my problems into the simple example above because I seem to have a fundamental misunderstanding about how fibers and EventMachine should be used together that is preventing me from using the more complex frameworks effectively.</p>