My first time dealing with sinatra and parallel em-http-request. And i dont know how to combine/merge into one results and when to EventMachine.stop? . Consider this:
get '/data/:query' do
content_type :json
EventMachine.run do
http1 = EventMachine::HttpRequest.new('v1/').get
http2 = EventMachine::HttpRequest.new('v2/').get
http1.errback { p 'Uh oh nooooooo'; EventMachine.stop }
http1.callback {
// do some operation http1.repsonse
Crack::XML.parse(http1.response).to_json
EventMachine.stop
}
http2.callback {
// do some operation http2.response
Crack::XML.parse(http2.response).to_json
EventMachine.stop
}
end
somehow merge
return merged_result
end
Above example has a race condition - you'll stop the eventloop as soon as one of the requests has finished. To address this, you can use the built in "Multi" interface:
See em-http wiki page for more: https://github.com/igrigorik/em-http-request/wiki/Parallel-Requests#synchronizing-with-multi-interface