FileSaver saveAs function does not download all the files using Promise.allSettled

I have a TypeScript function that tries to download a large number of small documents concurrently. Here’s the code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const bulkDownload = async (analyses: FullAnalysesResponse[]) => {
setIsLoading(true);
const promises = analyses.map(async (analysis) => {
const documentInfo = await getDocumentInfo({ documentId: analysis.downloadFileId! });
const attachment = await downloadDocument({ documentId: analysis.downloadFileId! });
FileSaver.saveAs(new File([attachment], documentInfo.name, { type: documentInfo.mimeType }));
});
const results = await Promise.allSettled(promises);
setIsLoading(false);
results.forEach((result, index) => {
const analysisSerialNumber = analyses[index].deviceSerialNumber;
result.status === 'fulfilled'
? successfulQueries.push(analysisSerialNumber)
: failedQueries.push(analysisSerialNumber);
});
return { failedQueries, successfulQueries };
};
</code>
<code>const bulkDownload = async (analyses: FullAnalysesResponse[]) => { setIsLoading(true); const promises = analyses.map(async (analysis) => { const documentInfo = await getDocumentInfo({ documentId: analysis.downloadFileId! }); const attachment = await downloadDocument({ documentId: analysis.downloadFileId! }); FileSaver.saveAs(new File([attachment], documentInfo.name, { type: documentInfo.mimeType })); }); const results = await Promise.allSettled(promises); setIsLoading(false); results.forEach((result, index) => { const analysisSerialNumber = analyses[index].deviceSerialNumber; result.status === 'fulfilled' ? successfulQueries.push(analysisSerialNumber) : failedQueries.push(analysisSerialNumber); }); return { failedQueries, successfulQueries }; }; </code>
const bulkDownload = async (analyses: FullAnalysesResponse[]) => {
  setIsLoading(true);

  const promises = analyses.map(async (analysis) => {
    const documentInfo = await getDocumentInfo({ documentId: analysis.downloadFileId! });
    const attachment = await downloadDocument({ documentId: analysis.downloadFileId! });
    FileSaver.saveAs(new File([attachment], documentInfo.name, { type: documentInfo.mimeType }));
  });

  const results = await Promise.allSettled(promises);

  setIsLoading(false);

  results.forEach((result, index) => {
    const analysisSerialNumber = analyses[index].deviceSerialNumber;
    result.status === 'fulfilled'
      ? successfulQueries.push(analysisSerialNumber)
      : failedQueries.push(analysisSerialNumber);
  });

  return { failedQueries, successfulQueries };
};

The issue is that when I trigger this function to download multiple files at once, not all the files are downloaded. The number of downloaded files changes every time I run the function, and I never get all the files. All the API calls are working, so all the promises are successful. The issue seems to come from the FileSaver.saveAs function.

I also tried a version that uses a simple for...of loop, which works fine:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const bulkDownload = async (analyses: FullAnalysesResponse[]) => {
setIsLoading(true);
const successfulQueries: string[] = [];
const failedQueries: string[] = [];
for (const analysis of analyses) {
try {
const documentInfo = await getDocumentInfo({ documentId: analysis.downloadFileId! });
const attachment = await downloadDocument({ documentId: analysis.downloadFileId! });
FileSaver.saveAs(new File([attachment], documentInfo.name, { type: documentInfo.mimeType }));
successfulQueries.push(analysis.deviceSerialNumber);
} catch (error) {
failedQueries.push(analysis.deviceSerialNumber);
}
}
setIsLoading(false);
return { failedQueries, successfulQueries };
};
</code>
<code>const bulkDownload = async (analyses: FullAnalysesResponse[]) => { setIsLoading(true); const successfulQueries: string[] = []; const failedQueries: string[] = []; for (const analysis of analyses) { try { const documentInfo = await getDocumentInfo({ documentId: analysis.downloadFileId! }); const attachment = await downloadDocument({ documentId: analysis.downloadFileId! }); FileSaver.saveAs(new File([attachment], documentInfo.name, { type: documentInfo.mimeType })); successfulQueries.push(analysis.deviceSerialNumber); } catch (error) { failedQueries.push(analysis.deviceSerialNumber); } } setIsLoading(false); return { failedQueries, successfulQueries }; }; </code>
const bulkDownload = async (analyses: FullAnalysesResponse[]) => {
  setIsLoading(true);
  
  const successfulQueries: string[] = [];
  const failedQueries: string[] = [];

  for (const analysis of analyses) {
    try {
      const documentInfo = await getDocumentInfo({ documentId: analysis.downloadFileId! });
      const attachment = await downloadDocument({ documentId: analysis.downloadFileId! });
      FileSaver.saveAs(new File([attachment], documentInfo.name, { type: documentInfo.mimeType }));
      successfulQueries.push(analysis.deviceSerialNumber);
    } catch (error) {
      failedQueries.push(analysis.deviceSerialNumber);
    }
  }

  setIsLoading(false);

  return { failedQueries, successfulQueries };
};

The for...of version works reliably but is slower since it downloads the files sequentially. I would like to understand why the first (concurrent) function is not working as expected. I assumed that running the downloads concurrently would be more efficient.

Any insights on why this happens, and how to fix it while keeping the performance benefits of concurrent downloads?

18

I’m hesitant to answer this, because I fear there may be an element of “magic number” about it

What you want is to control the number of concurrent file downloads (i.e. not the API requests, since they seem to work fine as fast as you can request them), but this is not exactly possible, since FileSaver.js can’t tell you when a file has completed downloading. However, maybe with some tweaking of the “magic numbers” you can get a consistent (faster than one at a time) result.

So, the following code contains the allSettledConcurrent function that combines your .map and Promise.allSettled into one function

In case you’re wondering, I wrote this function, along with a suite of others (allConcurrent, throttleAllConcurrent, throttleAllSettledConcurrent, throttlePromise etc) years ago for various use cases

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// MAGIC numbers
const afterDownloadDelay = 100;
const concurrency = 10;
async function allSettledConcurrent(items, concurrency, fn) {
const results = new Array(items.length);
const queue = items.map((item, index) => ({ item, index }));
const doFn = async ({ item, index }) => {
try {
const value = await fn(item);
results[index] = { value, status: "fulfilled" };
} catch (reason) {
results[index] = { reason, status: "rejected" };
}
return queue.length && doFn(queue.shift());
};
const slots = queue.splice(0, concurrency).map(doFn);
await Promise.all(slots);
return results;
}
const bulkDownload = async (analyses: FullAnalysesResponse[]) => {
setIsLoading(true);
const results = await allSettledConcurrent(analyses, concurrency, async (analysis) => {
const documentInfo = await getDocumentInfo({ documentId: analysis.downloadFileId! });
const attachment = await downloadDocument({ documentId: analysis.downloadFileId! });
FileSaver.saveAs(new File([attachment], documentInfo.name, { type: documentInfo.mimeType }));
if (afterDownloadDelay) {
await new Promise(resolve => setTimeout(resolve, afterDownloadDelay));
}
});
setIsLoading(false);
results.forEach((result, index) => {
const analysisSerialNumber = analyses[index].deviceSerialNumber;
result.status === 'fulfilled'
? successfulQueries.push(analysisSerialNumber)
: failedQueries.push(analysisSerialNumber);
});
return { failedQueries, successfulQueries };
};
</code>
<code>// MAGIC numbers const afterDownloadDelay = 100; const concurrency = 10; async function allSettledConcurrent(items, concurrency, fn) { const results = new Array(items.length); const queue = items.map((item, index) => ({ item, index })); const doFn = async ({ item, index }) => { try { const value = await fn(item); results[index] = { value, status: "fulfilled" }; } catch (reason) { results[index] = { reason, status: "rejected" }; } return queue.length && doFn(queue.shift()); }; const slots = queue.splice(0, concurrency).map(doFn); await Promise.all(slots); return results; } const bulkDownload = async (analyses: FullAnalysesResponse[]) => { setIsLoading(true); const results = await allSettledConcurrent(analyses, concurrency, async (analysis) => { const documentInfo = await getDocumentInfo({ documentId: analysis.downloadFileId! }); const attachment = await downloadDocument({ documentId: analysis.downloadFileId! }); FileSaver.saveAs(new File([attachment], documentInfo.name, { type: documentInfo.mimeType })); if (afterDownloadDelay) { await new Promise(resolve => setTimeout(resolve, afterDownloadDelay)); } }); setIsLoading(false); results.forEach((result, index) => { const analysisSerialNumber = analyses[index].deviceSerialNumber; result.status === 'fulfilled' ? successfulQueries.push(analysisSerialNumber) : failedQueries.push(analysisSerialNumber); }); return { failedQueries, successfulQueries }; }; </code>
// MAGIC numbers
const afterDownloadDelay = 100;
const concurrency = 10;

async function allSettledConcurrent(items, concurrency, fn) {
    const results = new Array(items.length);
    const queue = items.map((item, index) => ({ item, index }));
    const doFn = async ({ item, index }) => {
        try {
            const value = await fn(item);
            results[index] = { value, status: "fulfilled" };
        } catch (reason) {
            results[index] = { reason, status: "rejected" };
        }
        return queue.length && doFn(queue.shift());
    };
    const slots = queue.splice(0, concurrency).map(doFn);
    await Promise.all(slots);
    return results;
}

const bulkDownload = async (analyses: FullAnalysesResponse[]) => {
    setIsLoading(true);

    const results = await allSettledConcurrent(analyses, concurrency, async (analysis) => {
        const documentInfo = await getDocumentInfo({ documentId: analysis.downloadFileId! });
        const attachment = await downloadDocument({ documentId: analysis.downloadFileId! });
        FileSaver.saveAs(new File([attachment], documentInfo.name, { type: documentInfo.mimeType }));
        if (afterDownloadDelay) {
            await new Promise(resolve => setTimeout(resolve, afterDownloadDelay));
        }
    });

    setIsLoading(false);

    results.forEach((result, index) => {
        const analysisSerialNumber = analyses[index].deviceSerialNumber;
        result.status === 'fulfilled'
            ? successfulQueries.push(analysisSerialNumber)
            : failedQueries.push(analysisSerialNumber);
    });

    return { failedQueries, successfulQueries };
};

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật