view raw
Ethan McTague Ethan McTague - 5 months ago 45
Ruby Question

How do I wait and send a response to an HTTP request at a later time?

I am developing an API using Sinatra on the server-side. I would like to have an HTTP request which is made, but continues to hang/wait and keep alive until a later event (another event) causes it to complete with a certain response value at a later time.

In other words:

get '/api/foo/:request_identifier' do
# some code here
wait_until_finished params[:request_identifier]

# When this URL is visited, the hanging request with the matching
# request identifier will complete, sending "foo response text" to the
# client.
get '/api/bar/:request_identifier' do
make_it_finish params[:request_identifier] "foo response text"
"bar response text"

How could I implement this, or something to this effect?

I have also considered having the client constantly making requests to the server polling for completed requests, but the high number of requests could result in an expensive internet bill.


I'd be careful with hanging requests as it is not a great user experience. That being said, if you need to have one thing finish before another, here are some options.

Here are some suggestions for you:

1) Use an event emitter

2) Use an async library

Without full context of your problem it is hard to recommend one over the other, however, based on what you've described it sounds like a "Promise" would solve your issue here, which is recommendation #2. It basically allows you to wait for one thing to finish before doing thing 2.