简体   繁体   English

等待在rails控制器中完成HTTP请求

[英]Wait for HTTP request to complete in rails controller

I have a scenario where my rails controller action has to make a API request to a backend business logic server which does a lot of computations and returns me the result. 我有一个场景,我的rails控制器动作必须向后端业务逻辑服务器发出API请求,该服务器执行大量计算并返回结果。

I'm thinking to show a loading page to the user and make the call asynchronous using Faye or any other option and redirect the user when the call is complete.. 我正在考虑向用户显示加载页面,并使用Faye或任何其他选项使调用异步,并在调用完成时重定向用户。

But even if I make the call asynchronous, the HTTP request needs to wait for the server to return the data after process, which would take around 20 seconds. 但即使我使调用异步,HTTP请求也需要等待服务器在进程后返回数据,这将花费大约20秒。

I would like to know what is the best way to make such calls in rails.? 我想知道在rails中进行此类调用的最佳方法是什么。

I had faced a similar situation, below is the route that I took: 我遇到了类似的情况,下面是我采取的路线:

  1. When the controller action is triggered a. 当触发控制器动作时a。 I fired off a 'async' request to the API using a worker(I used sidekiq) b. 我使用worker(我使用sidekiq)b向API发出了'异步'请求。 Loaded a 'AJAX' spinner gif on top of a modal 在模态上加载了一个'AJAX'旋转器gif

  2. The worker handling the API request runs on another thread which is synchronous and waits for the result from the API 处理API请求的worker在另一个同步的线程上运行,并等待来自API的结果

  3. When the processing is done, the worker fires off notification via 'Faye' which removes the modal and populates the data. 处理完成后,工作人员通过'Faye'发出通知,删除模态并填充数据。

Return an HTTP response with status 202 Accepted (for the request that need to take long to process) and start making AJAX requests(to a URL, eg /jobs/1) to check the status of the background job. 返回状态为202 Accepted的HTTP响应(对于需要花费很长时间才能处理的请求)并开始发出AJAX请求(到URL,例如/ jobs / 1)以检查后台作业的状态。 Once your job has finished, update it's status so that your Javascript(AJAX) can handle the result of that background job. 一旦你的工作完成,更新它的状态,以便你的Javascript(AJAX)可以处理该后台作业的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM