R
R
Roman Mirilaczvili2019-04-02 15:30:01
ruby
Roman Mirilaczvili, 2019-04-02 15:30:01

What's wrong with asynchronous code, EventMachine?

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

urls = [
  'http://example.com/',
  'https://www.cloudflare.com/robots.txt',
  'https://rubygems.org/gems/em-http-request/versions.atom',
  'https://www.cloudflare.com/robots.txt2', # 404 not found
  'http://twitter.com/robots.txt',
  # 'http://localhost/robots.txt',
]

def url_handler(url)
  http = EventMachine::HttpRequest.new(url).get

  http.errback {
  	puts "Oops #{url}"
  	puts '-'*20
  	EventMachine.stop
  }
  http.callback {
    puts "#{http.response_header.status} #{url}"
    # p http.response_header
    p http.response[0,50]
    puts '-'*20
    EventMachine.stop
  }
end

EventMachine.run do
  urls.each {|url| url_handler(url) }
end

Why is errback called?
Conclusion #1
200 example.com
"\n\n\n Example D"
--------------------
Oops https://www.cloudflare.com/robots.txt
--------------------
Oops https://rubygems.org/gems/em-http-request/versions.atom
--------------------
Oops https://www.cloudflare.com/robots.txt2
--------------------
Oops twitter.com/robots.txt
Conclusion #2
200 twitter.com/robots.txt
"#Google Search Engine Robot\nUser-agent: Googlebot\n"
--------------------
Oops example.com
--------------------
Oops https://www.cloudflare.com/robots.txt
--------------------
Oops https://rubygems.org/gems/em-http-request/versions.atom
--------------------
Oops https://www.cloudflare.com/robots.txt2
--------------------

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question