[英]How to notify HTTP client of the completion of a long task
I have a Node.js system that uploads a large number of objects to MongoDB and creates folders in dropbox for each object. 我有一个Node.js系统,该系统将大量对象上载到MongoDB,并在保管箱中为每个对象创建文件夹。 This takes around 0.5 seconds per object.
每个对象大约需要0.5秒。 In situations therefore where i have many objects this could take up to around a minute.
因此,在我有很多物体的情况下,这可能需要一分钟左右的时间。 What i currently do is notify the client that the array of objects has been accepted using a
202
response code. 我当前所做的是使用
202
响应代码通知客户端对象数组已被接受。 However how do i then notify the client of completion a minute later. 但是,我如何在一分钟后通知客户完成情况。
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)
},
Well the problem with making client request wait, is it will timeout after certain period or sometimes will show error with no response received
. 好了,让客户端请求等待的问题是它会在一定时间后超时,或者有时会显示错误而
no response received
。
What you can do is 你能做的是
- 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.
Or simply implement WebHook
or WebSockets
to maintain communication. 或者简单地实现
WebHook
或WebSockets
以维持通信。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.