Bryan
Bryan

Reputation: 2315

How can I block on an EventMachine deferrable object?

I'm making a request to another server as part of a POST method to my Sinatra application. The library I'm using to make the request is an EventMachine library that immediately returns an EM::Deferrable object when a request is made, but I need to block in the controller method until the asynchronous request completes so I can return a partial with data returned in the request. What's the best approach for doing this?

Upvotes: 0

Views: 640

Answers (2)

tbuehlmann
tbuehlmann

Reputation: 9110

One solution would be to use async_sinatra and an EM based webserver like Thin. With async_sinatra you would have a body method for explicit rendering. It would work like this:

require 'sinatra/async'
require 'em-http-request'

class Application < Sinatra::Base
  register Sinatra::Async

  apost '/' do
    http = EM::HttpRequest.new('http://www.google.de/').get

    http.callback do
      body do
        # your http processing in here, will be rendered
      end
    end

    http.errback do
      body { 'error' }
    end
  end
end

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230521

When you block on an evented API, you get worst of the two worlds.

I would try to avoid calls through EM in favor of more 'traditional' methods (a-la curl).

If this is not possible, then I would return an empty partial and have client poll the server for updates.

Upvotes: 0

Related Questions