简体   繁体   English

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

[英]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.

相关问题 使用Angular的resolve:时,兑现承诺的最佳方法是什么? - What is the best way to chain promises when using Angular's resolve: {}? 在蓝鸟中使用“ .then”链接异步功能。 什么是最好的方法? - Chaining async functions in bluebird with “.then”. What is the best way? 在 Vue 中保存异步数据的最佳方法是什么? - What is the best way to save async data in Vue? 编写通过JavaScript而非纯HTML解析的链接的最佳方法是什么? (jQuery选项卡) - What's the best way to write links that resolve by JavaScript rather than pure HTML? (jQuery tabs) 从 React 中的异步调用批处理 state 更新的最佳方法是什么? - What's the best way to batch state updates from async calls in React? 在每次迭代上执行带有超时的async.series的最佳方法是什么? - What's the best way to perform an async.series with a timeout on each iteration? 重写这个的最好方法是什么? - What's the best way to rewrite this? 解决 Node.js promise 的最佳方法是什么? - What is the best way to resolve Node.js promise? 在 Firebase 的 onAuthStateChanged() 中使用 async/await 的最佳方法是什么? - What is the best way to use async/await inside onAuthStateChanged() of Firebase? 我们如何使用异步,以及nodeJS的最佳方法是什么 - How do we use Async, and what is the best way in nodeJS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM