[英]How can I modify the array passed to Promise.all
我的 node.js class 正在異步地從文件系統中遞歸加載文件。
在所有文件完成加載之前,我的 class 的其他方法無效,因此我定義了一個承諾數組,並在執行依賴於加載完成的方法之前對數組執行Promise.all()
。
當代碼發現每個文件或目錄時,它會將一個新的 promise 添加到數組中,以便該數組最終包含一個 promise 用於每個掃描的目錄和加載的每個文件。 我已經證實這是按設計工作的。
問題是Promise.all()
似乎只等待調用時已經在數組中的承諾,而不等待在調用Promise.all()
之后添加到數組中的承諾,所以 ZB321DE3BDC299EC807E由Promise.all()
返回的問題在所有文件加載之前解決。
是的,我確實確保在解決當前的 promise 之前將新的承諾添加到數組中以避免這種競爭條件。
假設在這種情況下我不能使用Promise.all()
,最好的選擇是什么?
我認為您應該首先遍歷文件系統的樹以獲取所有文件的路徑並將它們存儲在一個數組中,然后是Promise.all
那個數組。
像這樣的東西:
(我正在使用 lodash)
async function getPaths(dir) { const files = []; const promises = []; const contents = await fs.readdir(dir); for (const content of contents) { if(_.endsWith(content, '.js')) { // only get JS files files.push(path.resolve(dir, content)); } else { promises.push(getPaths(path.resolve(dir, content))); } } let subDirFiles = await Promise.all(promises); subDirFiles = _.flatten(subDirFiles); return _.union(files, subDirFiles); // contain all files paths from a root `dir` }
感謝您提供如何知道所有承諾何時在動態“可迭代”參數中得到解決的鏈接? . 使用來自該線程的信息,我能夠提出一個可行的解決方案,如下所示:
private readonly loadingPromises: Promise<any>[];
private async finishLoading(): Promise<void> {
var completedCount = 0;
while (this.loadingPromises.length != completedCount) {
var waitCount = this.loadingPromises.length;
await Promise.all(this.loadingPromises);
completedCount = waitCount;
}
this.loadingPromises.length = 0;
}
async somePublicMethod() {
return this.finishLoading().then(() => {
//... do stuff here
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.