简体   繁体   English

重试不成功的异步操作 - 如何避免在 EsLint 中的循环内等待(no-await-in-loop)?

[英]Retry asynchronous operations that were unsuccessfull - How to avoid await inside of loops (no-await-in-loop) in EsLint?

I have an array of tours from JSON and import all of them into a database.我有一系列来自 JSON 的旅行,并将它们全部导入数据库。

I use for-loop because I want to extract all the error tours into another file so I can fix it and re-import again later.我使用 for-loop 是因为我想将所有错误之旅提取到另一个文件中,以便我可以修复它并稍后再次重新导入。

Here is my code, and it works as expected.这是我的代码,它按预期工作。


const importData = async () => {


  const tours = JSON.parse(
    await fs.readFile(path.join(__dirname, 'data', 'final.json'), 'utf8')
  );
 

  const errorTours = [];


  for (let i = 0; i < tours.length; i += 1) {

   const tour = tours[parseInt(i, 10)];

     try {
       await Tour.create(tour);
     } catch (e) {
       errorTours.push({ tour, error: e });
     }
  }


  await fs.writeFile('errorTour.json', JSON.stringify(errorTours));

  console.log('finished!!! :tada:');
}

but I got "Disallow await inside of loops (no-await-in-loop)" EsLint Error.但我得到“不允许在循环内等待(无等待循环)”EsLint 错误。

Performing an operation on each element of an iterable is a common task.对可迭代的每个元素执行操作是一项常见任务。 However, performing an await as part of each operation is an indication that the program is not taking full advantage of the parallelization benefits of async/await.但是,将 await 作为每个操作的一部分执行表明程序没有充分利用 async/await 的并行化优势。

Usually, the code should be refactored to create all the promises at once, then get access to the results using Promise.all().通常,应该重构代码以一次创建所有 Promise,然后使用 Promise.all() 访问结果。 Otherwise, each successive operation will not start until the previous one has completed.否则,每个后续操作将在前一个操作完成之前不会开始。

Maybe in my case, the Promise.allSettled() suit better, right?也许在我的情况下, Promise.allSettled()更适合,对吧?

I'm new in JS and quite confused about how to change my async await code to Promise code to using Promise.allSettled.我是 JS 新手,对如何将异步等待代码更改为 Promise 代码以使用 Promise.allSettled 感到非常困惑。

Or is there any better way to retry asynchronous operations that were unsuccessful?或者有没有更好的方法来重试不成功的异步操作?

Can you guys show me the direction in this case?在这种情况下,你们能告诉我方向吗?

Thanks,谢谢,

How about this?这个怎么样?

 const TourPromises = tours.map(tour => Tour
    .create(tour)
    .catch(e => errorTours.push({tour, error: e}))
  )
 await Promise.all(TourPromises);

Good Luck...祝你好运...

Here is my tried, thank @Atlante Avila and Eslint docs这是我的尝试,感谢@Atlante Avila 和Eslint 文档

  const TourPromises = [];
  for (let i = 0; i < tours.length; i += 1) {
    const tour = tours[parseInt(i, 10)];

    TourPromises.push(
      Tour.create(tour).catch((e) => {
        errorTours.push({ tour, error: e });
      })
    );
  }

  await Promise.all(TourPromises);

old code: Took 5466.025282999966 milliseconds.旧代码:耗时 5466.025282999966 毫秒。

new code: Took 1682.5688519999385 milliseconds.新代码:耗时 1682.5688519999385 毫秒。

Look quite better,看起来好多了,

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

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