我如何等待并稍后发送对 HTTP 请求的响应?
How do I wait and send a response to an HTTP request at a later time?
我正在服务器端使用 Sinatra 开发 API。我想要一个已发出的 HTTP 请求,但会继续 hang/wait 并保持活动状态,直到稍后的事件(另一个事件)导致它在稍后的时间以某个响应值完成。
换句话说:
get '/api/foo/:request_identifier' do
# some code here
wait_until_finished params[:request_identifier]
end
# 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"
end
我怎样才能实现这个,或者类似的东西?
我也考虑过让客户端不断向服务器发出请求以轮询已完成的请求,但是大量请求可能会导致昂贵的互联网账单。
我会小心处理挂起的请求,因为这不是很好的用户体验。话虽这么说,如果你需要先完成一件事,这里有一些选择:
- 使用 event emitter
- 使用 async library
如果没有您的问题的完整背景,很难推荐一个优于另一个,但是,根据您的描述,听起来 "Promise" 可以解决您的问题,这是建议 #2 .它基本上允许你在做第二件事之前等待一件事完成。
我正在服务器端使用 Sinatra 开发 API。我想要一个已发出的 HTTP 请求,但会继续 hang/wait 并保持活动状态,直到稍后的事件(另一个事件)导致它在稍后的时间以某个响应值完成。
换句话说:
get '/api/foo/:request_identifier' do
# some code here
wait_until_finished params[:request_identifier]
end
# 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"
end
我怎样才能实现这个,或者类似的东西?
我也考虑过让客户端不断向服务器发出请求以轮询已完成的请求,但是大量请求可能会导致昂贵的互联网账单。
我会小心处理挂起的请求,因为这不是很好的用户体验。话虽这么说,如果你需要先完成一件事,这里有一些选择:
- 使用 event emitter
- 使用 async library
如果没有您的问题的完整背景,很难推荐一个优于另一个,但是,根据您的描述,听起来 "Promise" 可以解决您的问题,这是建议 #2 .它基本上允许你在做第二件事之前等待一件事完成。