ruby - Why my eventmachine client code doesn't work asynchronously? -
def index p "index, #{fiber.current.object_id}" # <- #1 eventmachine.run { http = eventmachine::httprequest.new('http://google.com/').get :query => {'keyname' => 'value'} http.errback { p "uh oh, #{fiber.current.object_id}"; em.stop } # <- #2 http.callback { p "#{http.response_header.status}, #{fiber.current.object_id}" # <- #3 p "#{http.response_header}" p "#{http.response}" eventmachine.stop } } render text: 'test1' end
in code, expected getting different fiber
id @ #1
, #2
, #3
line. fiber objects' id same. tried thread.current.object_id
, same result too.
misunderstaning? code executes asynchronously?
p.s i'm using ruby 2.0
, code running rails4
http://ruby-doc.org/core-2.0/fiber.html
fibers primitives implementing light weight cooperative concurrency in ruby. means of creating code blocks can paused , resumed, threads. main difference never preempted , scheduling must done programmer , not vm.
where in code scheduling fibers, e.g. calling fiber.yield or my_fiber.resume?
current() → fiber
returns current fiber. need require 'fiber' before using method. if not running in context of fiber method return root fiber.
where in code have created additional fibers, e.g. fiber.new ...?
is code executes asynchronously?
require 'em-http-request' require 'fiber' puts fiber.current.object_id def index p "index, #{fiber.current.object_id}" # <- #1 eventmachine.run { http = eventmachine::httprequest.new('http://google.com/').get :query => {'keyname' => 'value'} http.errback { p "#{uh oh}, #{fiber.current.object_id}"; em.stop } # <- #2 http.callback { p "#{http.response_header.status}, #{fiber.current.object_id}" # <- #3 p "#{http.response_header}" p "#{http.response}" eventmachine.stop } } #render text: 'test1' end index() --output:-- 2157346420 "index, 2157346420" "301, 2157346420" "{\"location\"=>\"http://www.google.com/?keyname=value\", \"content_type\"=>\"text/html; charset=utf-8\", \"date\"=>\"mon, 22 jul 2013 08:44:35 gmt\", \"expires\"=>\"wed, 21 aug 2013 08:44:35 gmt\", \"cache_control\"=>\"public, max-age=2592000\", \"server\"=>\"gws\", \"content_length\"=>\"233\", \"x_xss_protection\"=>\"1; mode=block\", \"x_frame_options\"=>\"sameorigin\", \"connection\"=>\"close\"}" "<html><head><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n<title>301 moved</title></head><body>\n<h1>301 moved</h1>\nthe document has moved\n<a href=\"http://www.google.com/?keyname=value\">here</a>.\r\n</body></html>\r\n"
nope.
and error:
http.errback { p "#{uh oh}" ...
Comments
Post a Comment