[英]Elegant solution - Nested for loops (eslint no-await-in-loop)
[英]Retry asynchronous operations that were unsuccessfull - How to avoid await inside of loops (no-await-in-loop) in EsLint?
我有一系列來自 JSON 的旅行,並將它們全部導入數據庫。
我使用 for-loop 是因為我想將所有錯誤之旅提取到另一個文件中,以便我可以修復它並稍后再次重新導入。
這是我的代碼,它按預期工作。
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:');
}
但我得到“不允許在循環內等待(無等待循環)”EsLint 錯誤。
對可迭代的每個元素執行操作是一項常見任務。 但是,將 await 作為每個操作的一部分執行表明程序沒有充分利用 async/await 的並行化優勢。
通常,應該重構代碼以一次創建所有 Promise,然后使用 Promise.all() 訪問結果。 否則,每個后續操作將在前一個操作完成之前不會開始。
也許在我的情況下, Promise.allSettled()更適合,對吧?
我是 JS 新手,對如何將異步等待代碼更改為 Promise 代碼以使用 Promise.allSettled 感到非常困惑。
或者有沒有更好的方法來重試不成功的異步操作?
在這種情況下,你們能告訴我方向嗎?
謝謝,
這個怎么樣?
const TourPromises = tours.map(tour => Tour
.create(tour)
.catch(e => errorTours.push({tour, error: e}))
)
await Promise.all(TourPromises);
祝你好運...
這是我的嘗試,感謝@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);
舊代碼:耗時 5466.025282999966 毫秒。
新代碼:耗時 1682.5688519999385 毫秒。
看起來好多了,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.