Exercise 14: Fetch with Progress Tracking

Problem Statement

Function `fetchWithProgress(url, onProgress)` banao jo fetch progress track kare. Example: fetchWithProgress(url, (loaded, total) => console.log(loaded/total))

Sample Output:

await fetchWithProgress(url, (loaded, total) => console.log(loaded/total))
// Calls onProgress with loaded/total

Solution

const fetchWithProgress = async (url, onProgress) => {
  const res = await fetch(url);
  const reader = res.body.getReader();
  const contentLength = +res.headers.get("content-length");
  let received = 0;
  const chunks = [];
  while (true) {
    const {done, value} = await reader.read();
    if (done) break;
    chunks.push(value);
    received += value.length;
    onProgress(received, contentLength);
  }
  return new Response(new Blob(chunks));
};

Explanation

Overall Goal:

  • Fetch progress track karna.

Real world:

  • File downloads: progress bars.
  • Large requests: progress tracking.