۲۸ ژوئیه ۲۰۲۱
این محتوا تنها در این زبان‌ها موجود است: عربي, English, Español, Français, Indonesia, Italiano, 日本語, 한국어, Русский, Türkçe, Українська, Oʻzbek, 简体中文. لطفاً به ما

Fetch: Download progress

The fetch method allows to track download progress.

Please note: there’s currently no way for fetch to track upload progress. For that purpose, please use XMLHttpRequest, we’ll cover it later.

To track download progress, we can use response.body property. It’s a ReadableStream – a special object that provides body chunk-by-chunk, as it comes. Readable streams are described in the Streams API specification.

Unlike response.text(), response.json() and other methods, response.body gives full control over the reading process, and we can count how much is consumed at any moment.

Here’s the sketch of code that reads the response from response.body:

// instead of response.json() and other methods
const reader = response.body.getReader();

// infinite loop while the body is downloading
while(true) {
  // done is true for the last chunk
  // value is Uint8Array of the chunk bytes
  const {done, value} = await reader.read();

  if (done) {
    break;
  }

  console.log(`Received ${value.length} bytes`)
}

The result of await reader.read() call is an object with two properties:

  • donetrue when the reading is complete, otherwise false.
  • value – a typed array of bytes: Uint8Array.
لطفاً توجه کنید:

Streams API also describes asynchronous iteration over ReadableStream with for await..of loop, but it’s not yet widely supported (see browser issues), so we use while loop.

We receive response chunks in the loop, until the loading finishes, that is: until done becomes true.