gpt4 book ai didi

Ruby EventMachine - 如何将值从 EM::Deferrable 返回到主 EM 循环?

转载 作者:数据小太阳 更新时间:2023-10-29 07:27:31 31 4
gpt4 key购买 nike

我现在正在使用 EventMachine 玩了几天,恕我直言,它的学习曲线很陡;-) 我尝试通过触发回调中需要的 HttpHeaderCrawler.query() 来返回哈希。但是在这种情况下我得到的不是散列 {'http_status' => xxx, 'http_version' => xxx} 而是一个 EventMachine::HttpClient 对象本身。

我想保持 EM.run block 干净,并想在自己的类/模块中执行所有逻辑,那么如何将这样的值返回到主循环中以通过回调访问它?非常感谢 ;-)

#!/usr/bin/env ruby

require 'eventmachine'
require 'em-http-request'

class HttpHeaderCrawler
include EM::Deferrable

def query(uri)
http = EM::HttpRequest.new(uri).get
http.callback do
http_header = {
"http_status" => http.response_header.http_status,
"http_version" => http.response_header.http_version
}
puts "Returns to EM main loop: #{http_header}"
succeed(http_header)
end
end
end

EM.run do
domains = ['http://www.google.com', 'http://www.facebook.com', 'http://www.twitter.com']
domains.each do |domain|
hdr = HttpHeaderCrawler.new.query(domain)
hdr.callback do |header|
puts "Received from HttpHeaderCrawler: #{header}"
end
end
end

此代码段产生以下输出:

Returns to EM main loop: {"http_status"=>302, "http_version"=>"1.1"}
Received from HttpHeaderCrawler: #<EventMachine::HttpClient:0x00000100d57388>
Returns to EM main loop: {"http_status"=>301, "http_version"=>"1.1"}
Received from HttpHeaderCrawler: #<EventMachine::HttpClient:0x00000100d551a0>
Returns to EM main loop: {"http_status"=>200, "http_version"=>"1.1"}
Received from HttpHeaderCrawler: #<EventMachine::HttpClient:0x00000100d56280>

最佳答案

我认为问题是 #query 返回 http.callback,它返回 http 对象本身,而它应该返回 self,即HttpHeaderCrawler。看看这是否有效。

def query(uri)
http = EM::HttpRequest.new(uri).get
http.callback do
http_header = {
"http_status" => http.response_header.http_status,
"http_version" => http.response_header.http_version
}
puts "Returns to EM main loop: #{http_header}"
succeed(http_header)
end
self
end

关于Ruby EventMachine - 如何将值从 EM::Deferrable 返回到主 EM 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7910289/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com