Em-synchrony 示例代码未按预期工作

发布于 2024-12-29 10:04:06 字数 1009 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黑寡妇 2025-01-05 10:04:06

您需要使用 EventMachine::HttpRequest 的扩展版本,它知道如何使用 EventMachine.synchrony

依次更改

require 'em-http-request'

require "em-synchrony/em-http" 

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 with EventMachine.synchrony.

Change

require 'em-http-request'

to

require "em-synchrony/em-http" 

This in turn will require "em-http-request" and will patch #get, #head, #post, #delete, #put methods of EventMachine::HttpRequest to work with Fibers.

Here is the link to source code of em-synchrony/em-http.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文