我正在服务器端使用Sinatra开发API。我希望有一个HTTP请求,但是继续挂起/等待并保持活动状态,直到稍后的事件(另一个事件)导致它在稍后的时间内以某个响应值完成。
换句话说:
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
我怎么能实现这个,或者这个效果呢?
我还考虑让客户端不断向服务器请求轮询已完成的请求,但是大量请求可能导致昂贵的互联网账单。
答案 0 :(得分:2)
我会小心处理挂起请求,因为它不是一个出色的用户体验。话虽这么说,如果你需要在另一个之前完成一件事,这里有一些选择:
如果没有问题的完整背景,很难推荐一个在另一个上面,但是,根据你所描述的内容,听起来像“Promise”会解决你的问题,这是推荐#2。它基本上允许你在做事情2之前等待一件事情完成。