【问题标题】:How can I receive real-time updates from a long asynchronous process?如何从长的异步进程接收实时更新?
【发布时间】:2017-07-18 20:07:21
【问题描述】:

我正在编写一个小型的内部 Web 应用程序,它读取表单数据并创建一个 Excel 文件,然后通过电子邮件发送给用户。

但是,我很难理解如何在流程完成时为用户实现实时更新。有时该过程需要 10 秒,有时该过程需要 5 分钟。

目前,用户在看到任何结果之前要等到该过程完成 - 因为该过程正在完成,他们看不到任何更新。前端在显示报告信息之前等待服务器的201响应,并且用户被“阻止”,直到RC完成。

我很难理解如何异步启动报告创建 (RC) 过程,同时允许用户导航到网站的其他页面。或查看后台发生的更新。我应该在这里澄清一下,RC 过程中的一些步骤使用了 Promises。

我想每秒轮询一次服务器以获取有关正在生成的报告的更新。

这里有一些简单的代码来澄清我的理解:

端点

// CREATE REPORT
router.route('/report')
  .post(function(req, res, next) {

    // Generate unique ID to keep track of report later on.
    const uid = generateRandomID();

    // Start report process ... this should keep executing even after a response (201) is returned.
    CustomReportLibrary.createNewReport(req.formData, uid);

    // Respond with a successful creation.
    res.status(201);
  }
}

// GET REPORT
router.route('/report/:id')
.get(function(req, res, next){

  // Get our report from ID.
  let report = CustomReportLibrary.getReport(req.params.id);

  // Respond with report data
  if(report) { res.status(200).json(report); }
  else { res.status(404); }
}

CustomReportLibrary

// Initialize array to hold reports
let _dataStorage = []; 

function createNewReport(data, id) {

  // Create an object to store our report information
  let reportObject = {
    id: id,
    status: 'Report has started the process',
    data: data  
  }

  // Add new report to global array.
  _dataStorage.push(reportObject);

  // ... continue with report generation. Assume this takes 5 minutes.
  // ...
  // ... update _dataStorage[length-1].status after each step
  // ...
  // ... finish generation.
}

function getReport(id) {
  // Iterate through array until report with matching ID is found.
  // Return report if match is found.
  // Return null if no match is found.
}

据我了解,CustomerReportLibrary.createNewReport() 即使在返回 201 响应后也会在后台执行。在前端,我会每隔一段时间对/report/:id 进行一次AJAX 调用,以获取有关我的报告的更新。这是正确的方法吗?有没有更好的方法来做到这一点?

【问题讨论】:

    标签: ajax node.js rest express asynchronous


    【解决方案1】:

    我认为你是在正确的方式。 HTTP 202(请求已被接受处理,但处理尚未完成)是处理您的情况的正确方法。

    可以这样做:

    1. 客户端发送POST /reports,服务器开始创建新报告并返回:

      202 Accepted
      Location: http://api.domain.com/reports/1
      
    2. 客户端发出GET /reports/1 以获取报告状态

    上述所有流程都是异步的,因此不会阻止用户。

    【讨论】:

    • 谢谢!我不知道 202 响应。我会更加关注 HTTP 响应。
    猜你喜欢
    • 2020-06-20
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2023-04-09
    • 2018-10-20
    • 1970-01-01
    • 2019-08-12
    相关资源
    最近更新 更多