title: em-http-request - Where do I put my EventMachine.stop?
body: <p>I want to iterate over a JSON-API every 10th second, and do a second HTTP-request using the same connection (keepalive) if a certain key was found in the JSON-data. If I do not place  <code>EM.stop</code> in my code, the program stops to wait after finishing processing in req1.callback.</p>
  
  <p>If I put <code>EM.stop</code> inside <code>req2.callback</code> it works and is iterating as expected.</p>
  
  <p>But if the JSON-document did not include the key <code>foobar</code>, the program stops to wait after finishing processing in req1.callback.</p>
  
  <p>If I add <code>EM.stop</code> in the last line inside req1.callback, req2.callback is aborted if the JSON-document had the key <code>foobar</code>.</p>
  
  <p>How should I properly place <code>EM.stop</code> to make it iterate if the JSON-document had what I wanted or not?</p>
  
  <pre><code>require 'eventmachine'
  require 'em-http'
  
  loop do    
    EM.run do
      c = EM::HttpRequest.new 'http://api.example.com/'
  
      req1 = c.get :keepalive =&gt; true
      req1.callback do
        document = JSON.parse req1.response
        if document.has_key? foobar   
          req2 = c.get :path =&gt; '/data/'
          req2.callback do
            puts [:success, 2, req2]
            puts "\n\n\n"
            EM.stop
          end
        end
      end
    end
  
    sleep 10
  end
  </code></pre>