我有一个快速服务器,它接受许多上传的文件并转换/翻译其中的一些。
解决许多异步操作的最佳(简单/高效)方法是什么?我可以制作一个数组并将其用作已完成文件的 list ,但这感觉很糟糕,我担心如果有任何文件错误,该过程将永远无法完成,并且永远不会通知用户他们的文件已完成/准备好。
我确定我不是第一个遇到这个问题的人,所以非常欢迎任何关于这个问题的博客文章/在线书籍。
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
最佳答案
只要所有异步任务都返回一个 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))
注意:前面假设您希望首先进行所有处理,然后在处理完成后保存所有内容。也可以使处理瘫痪并保存到单独的 promise 链中,并在末尾使用 Promise.all()
将它们全部收集起来。这个例子更容易理解。
关于javascript - 解决异步任务的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51487484/