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,