Question

I have the following code:

require 'rubygems'
require 'eventmachine'
require 'em-http'
require 'sinatra/base'
require 'sinatra/async'

class Api < Sinatra::Base
  register Sinatra::Async

  aget '/1' do
      EventMachine.run {
         http = EventMachine::HttpRequest.new( "http://www.google.com").get(:timeout => 5)
         http.callback { puts "h2" ;ret_val = http.response; EventMachine.stop}
         http.errback {puts "was h2ere1" ;ret_val = nil; EventMachine.stop}
       }
       body "done processing 1"
  end

  aget '/2' do
       body "done processing 2"
  end

end

When I issue the following, it works well:

 curl http://localhost:3000/2

But, when I issue the following request, it prints "h2" and the application silently quits:

 curl http://localhost:3000/1

Any help will be appreciated. Thanks!

Was it helpful?

Solution

If your web server (Eg. thin) is based on EventMachine, then the EventMachine.stop line will actually stop the webserver as well as the EventMachine instance created by EventMachine.run.

I can't find a way to stop nested EventMachines like this. My advice - use Weary or another non-blocking HTTP request library.

OTHER TIPS

Sinatra::Async provides it's own body helper that needs to be called from within the EventMachine loop. Also worth noting: if you're running Sinatra through Thin, you shouldn't call EM.run explicitly, as Sinatra is already operating within an EventMachine loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top