Em-synchrony 示例代码未按预期工作
em-synchrony 文档链接到本文< /a> 这意味着使用 Fiber:
require 'eventmachine'
require 'fiber'
require 'em-http-request'
def http_get(url)
f = Fiber.current
http = EventMachine::HttpRequest.new(url).get
# resume fiber once http call is done
http.callback { f.resume(http) }
http.errback { f.resume(http) }
return Fiber.yield
end
EventMachine.run do
Fiber.new {
page = http_get('http://myurl')
puts "Fetched page: #{page.response}"
EventMachine.stop
}.resume
end
... 的这段代码相当于使用 em-synchrony: 的更简单的代码:
require 'em-synchrony'
require 'em-http-request'
EventMachine.synchrony do
page = EventMachine::HttpRequest.new("http://myurl").get
p "No callbacks! Fetched page: #{page.response}"
EventMachine.stop
end
但是运行两者会产生不同的结果。在第一个中,纤维会屈服直到 HTML 响应返回,而第二个似乎立即打印而不等待响应,因此打印的响应为空。我是否误读或输入错误,或者该文章实际上暗示了错误的事情?
The em-synchrony documentation links to this article which implies that this code with fiber:
require 'eventmachine'
require 'fiber'
require 'em-http-request'
def http_get(url)
f = Fiber.current
http = EventMachine::HttpRequest.new(url).get
# resume fiber once http call is done
http.callback { f.resume(http) }
http.errback { f.resume(http) }
return Fiber.yield
end
EventMachine.run do
Fiber.new {
page = http_get('http://myurl')
puts "Fetched page: #{page.response}"
EventMachine.stop
}.resume
end
...is equivalent to this much simpler code using em-synchrony:
require 'em-synchrony'
require 'em-http-request'
EventMachine.synchrony do
page = EventMachine::HttpRequest.new("http://myurl").get
p "No callbacks! Fetched page: #{page.response}"
EventMachine.stop
end
However running the two produces different results. In the first the fiber yields until the HTML response comes back, while the second seems to print immediately without waiting for the response and as a result the printed response is empty. Am I misreading or mistyping, or is the article actually suggesting the wrong thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用
EventMachine::HttpRequest
的扩展版本,它知道如何使用EventMachine.synchrony
。依次更改
为
This 将需要“em-http-request”,并将修补
EventMachine::HttpRequest
的#get、#head、#post、#delete、#put
方法> 使用纤维。这是 em 源代码的链接-synchrony/em-http。
You need to use extended version of
EventMachine::HttpRequest
that knows how to work withEventMachine.synchrony
.Change
to
This in turn will require "em-http-request" and will patch
#get, #head, #post, #delete, #put
methods ofEventMachine::HttpRequest
to work with Fibers.Here is the link to source code of em-synchrony/em-http.