0

I'm new to coding and was trying to implement download progress.Below is my code.

let btn = document.querySelector("#img");
btn.addEventListener("click", loadimage);
function loadimage() {
  fetch("https://reqres.in/invalid-url")
    .then(async (res) => {
      let contLength = res.headers.get("content-length");
      let reader = res.body.getReader();
      let downloaded_data = 0; 
      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          console.log("completed");
          break;
        }
        downloaded_data += value.length;
        console.log(downloaded_data);
      }
    })
    .catch(function (err) {
      console.log("catch block");
      console.log(err);
    });
}`  

` This is the error I'm getting.(not getting caught by catch block)

`GET https://reqres.in/invalid-url 404`
`6939`
`completed`

Why inspite of error, function in then block is getting invoked. I have tried different APIs but all are resulting same

Baba
  • 11
  • 3

2 Answers2

0

You have to check the response.ok in the then.

https://stackoverflow.com/a/38236296/16906055

mseyfayi
  • 116
  • 5
-1

Using await instead of that and try writing like this code:

// Step 1: start the fetch and obtain a reader
let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits?per_page=100');

const reader = response.body.getReader();

// Step 2: get total length
const contentLength = +response.headers.get('Content-Length');

// Step 3: read the data
let receivedLength = 0; // received that many bytes at the moment
let chunks = []; // array of received binary chunks (comprises the body)
while(true) {
  const {done, value} = await reader.read();

  if (done) {
    break;
  }

  chunks.push(value);
  receivedLength += value.length;

  console.log(`Received ${receivedLength} of ${contentLength}`)
}

// Step 4: concatenate chunks into single Uint8Array
let chunksAll = new Uint8Array(receivedLength); // (4.1)
let position = 0;
for(let chunk of chunks) {
  chunksAll.set(chunk, position); // (4.2)
  position += chunk.length;
}

// Step 5: decode into a string
let result = new TextDecoder("utf-8").decode(chunksAll);

// We're done!
let commits = JSON.parse(result);
alert(commits[0].author.login);

Reference: https://javascript.info/fetch-progress