我正在使用以下代码运行几个HTTP请求,但第二个请求(req2)始终返回到errback。
我错过了一些明显的东西吗?
request_options = {
:body => " ",
:keepalive => true,
:head => {
'content-type' => 'application/json',
'accept' => 'application/json',
'Accept-Encoding' => 'gzip,deflate,sdch'
}
}
EM.run do
request_options[:path] = '/default/path'
conn = EM::HttpRequest.new 'https://www.example.com'
req1 = conn.post request_options
req1.errback { p 'Uh, oh'; EM.stop }
req1.callback do
doc = JSON.parse req1.response
# do stuff with doc
request_options[:body] = 'post-data'
request_options[:path] = '/new/path'
req2 = conn.post request_options
req2.errback { p 'Uh, oh'; EM.stop }
req2.callback do
puts req2.response
EM.stop
end
end
end
答案 0 :(得分:3)
我使用 EM-Synchrony
解决了我的问题gem install em-synchrony
安装了这个gem后,我可以使用以下代码来使代码按预期工作。
request_options = {
:body => " ",
:keepalive => true,
:head => {
'content-type' => 'application/json',
'accept' => 'application/json',
'Accept-Encoding' => 'gzip,deflate,sdch'
}
}
EM.synchrony do
request_options[:path] = '/default/path'
conn = EM::HttpRequest.new 'https://www.example.com'
req1 = conn.post request_options
doc = JSON.parse req1.response
# do stuff with doc
request_options[:body] = 'post-data'
request_options[:path] = '/new/path'
req2 = conn.post request_options
puts req2.response
EM.stop
end
我想我只是对EM.run执行异步请求和di。
的方式感到困惑答案 1 :(得分:0)
您无法在响应回调中使用相同的连接对象。
确保为第二个请求创建新的EM::HttpRequest.new 'https://www.example.com'
。