[英]What's the best way to resolve async tasks?
I have an express server that accepts many uploaded files and converts/translates some of them. 我有一个快递服务器,它接受许多上载的文件并转换/翻译其中的一些文件。
What's the best (simple/efficient) way to resolve many asynchronous operations? 解决许多异步操作的最佳(简单/高效)方法是什么? I can make an array and use it like a checklist for which files are done, but this feels hack-y and I'm worried if any file errors the process will never complete, and the user will never be notified their files are finished/ready. 我可以制作一个数组,并将其用作完成文件的核对清单,但这感觉很骇人,我担心过程中将永远不会完成任何文件错误,并且永远也不会通知用户其文件已完成/准备。
I'm sure I'm not the first person to encounter this, so any blog articles/online books on this problem are very welcome. 我确定我不是第一个遇到此问题的人,因此非常欢迎您提供有关此问题的任何博客文章/在线书籍。
if (req.files)
req.files.forEach(saveFile);
else
console.log("\tDoesn't has multifiles", req.file);
function saveFile(file){
//file is renamed/moved (async)
if(isCertainFileType(file))
//convert and save converted file. Do not send a 200 or update the index until this is complete
}
updateDirIndex(); //index must be updated before sending 200 (reads all files in dir and writes to a file)
return res.status(200).send(index); //tell the browser their files are ready
As long as all your async tasks return a Promise
you can wait for them to all resolve using Promise.all()
. 只要所有异步任务都返回Promise
,就可以使用Promise.all()
等待它们全部解析。
let filesToProcess = [...]
// first process any files that need processing, returning an array of promises
let processPromises = filesToProcess.map(file => {
// if it needs processing, do it and return the promise
if (isCertainFileType(file)) {
return doProcessing(file)
}
// otherwise just return the file, any truthy value is considered a resolved promise
else {
return file
}
})
// then save all the files
let savePromises = processPromises.map(file => {
return saveFile(file)
})
// wait for all saves to complete (resolve), handle results or handle errors
Promise.all(savePromises)
.then((result) => {
// update the directory index here because we know everything was successful
updateDirIndex()
})
.catch((err) => console.error(err))
NOTE: The preceding made the assumption you wanted all processing to happen first, then save everything once the processing was complete. 注意:前面的假设是您希望先进行所有处理,然后在处理完成后保存所有内容。 It's also possible to paralyze the processing AND saving into separate promise chains and collect them all with a Promise.all()
at the end. 也有可能使处理过程陷入瘫痪并保存到单独的Promise.all()
链中,并在最后用Promise.all()
收集它们。 This example is just easier to understand. 这个例子更容易理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.