【问题标题】:How to notify HTTP client of the completion of a long task如何通知 HTTP 客户端长任务完成
【发布时间】:2018-12-11 15:48:48
【问题描述】:

我有一个 Node.js 系统,可以将大量对象上传到 MongoDB,并在 Dropbox 中为每个对象创建文件夹。每个对象大约需要 0.5 秒。因此,在我有很多对象的情况下,这可能需要大约一分钟。我目前所做的是使用202 响应代码通知客户端对象数组已被接受。但是,我如何在一分钟后通知客户完成。

app.post('/BulkAdd', function (req, res) {
    issues = []
    console.log(req.body)
    res.status(202).send({response:"Processing"});
    api_functions.bulkAdd(req.body).then( (failed, issues, success) => {
        console.log('done')
    })

});


bulkAdd: async function (req, callback) {
  let failed = []
  let issues = []
  let success = []
  i = 1

  await req.reduce((promise, audit) => {
    // return promise.then(_ => dropbox_functions.createFolder(audit.scanner_ui)
    let globalData;
  return promise.then(_ => this.add(audit)
      .then((data)=> {globalData = data; return dropbox_functions.createFolder(data.ui, data)}, (error)=> {failed.push({audit: audit, error: 'There was an error adding this case to the database'}); console.log(error)})
        .then((data)=>{console.log(data, globalData);return dropbox_functions.checkScannerFolderExists(audit.scanner_ui)},(error)=>{issues.push({audit: globalData, error: 'There was an error creating the case folder in dropbox'})})
         .then((data)=>{return dropbox_functions.moveFolder(audit.scanner_ui, globalData.ui)},(error)=>{issues.push({audit: globalData, error: 'No data folder was found so an empty one was created'}); return dropbox_functions.createDataFolder(globalData.ui)})
          .then(()=>success.push({audit:globalData}), issues.push({audit: globalData, error: 'Scanner folder found but items not moved'}))
    );
  }, Promise.resolve()).catch(error => {console.log(error)});
  return(failed, issues, success)

},

【问题讨论】:

  • 由于您没有包含任何代码,我只能建议使用setTimeout(()=>{ notifyUser(); }, 60000);
  • 如果您使用的是node,请查看Node Webhooks之类的内容
  • 一个HTTP响应是无状态的,IOW:一旦你返回了页面,就没有更多的交互了。有 2 个选项,1:使用长轮询请求,(但这可能很难做到正确)。 2. 使用 websockets 来传达进度。事实上,从一开始就使用 websockets 是 node.js 与 HTTP 客户端通信的一种非常好的方式。

标签: javascript node.js http express


【解决方案1】:

让客户端请求等待的问题是,它会在一段时间后超时,还是有时会显示no response received 错误。

你能做的是

 - Make client request to server to initiate the task, and return 200OK and keep doing your task on server. 
 - Now write a file on server after insertion of every object as status. 
 - Read the file from client every 5-10 sec to check if server has completed creating objects or not. 
 - Mean while your task is not completed on server, show status with completion percentage or some animation.

或者干脆实现WebHookWebSockets来保持通信。

【讨论】:

    猜你喜欢
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 2017-03-22
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多