繁体   English   中英

解决异步任务的最佳方法是什么?

[英]What's the best way to resolve async tasks?

我有一个快递服务器,它接受许多上载的文件并转换/翻译其中的一些文件。

解决许多异步操作的最佳(简单/高效)方法是什么? 我可以制作一个数组,并将其用作完成文件的核对清单,但这感觉很骇人,我担心过程中将永远不会完成任何文件错误,并且永远也不会通知用户其文件已完成/准备。

我确定我不是第一个遇到此问题的人,因此非常欢迎您提供有关此问题的任何博客文章/在线书籍。

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.all()链中,并在最后用Promise.all()收集它们。 这个例子更容易理解。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM