简体   繁体   中英

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.

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.

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.

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.

Usually, the code should be refactored to create all the promises at once, then get access to the results using 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?

I'm new in JS and quite confused about how to change my async await code to Promise code to using 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

  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.

new code: Took 1682.5688519999385 milliseconds.

Look quite better,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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