Joji
Joji

Reputation: 5646

What should the intermediate result that a fetch request returns be called? A blob or just response?

when we use fetch in JS to issue a get request, we normally do thing like this

fetch(endpoint).then(res => res.json()).then(result => ...)

However I was watching Wes Bos's JS 30 courses and he called the intermediate result that the fetch returns a blob as in

fetch(endpoint).then(blob => blob.json()).then(result => ...)

I found the definition for blob here https://developer.mozilla.org/en-US/docs/Web/API/Blob

I am not knowledgable enough to judge if Wes Bos was using the right term here to refer to it as blob and I have no ways to contact him directly and ask him. Hope I can find some answers here.

Upvotes: 0

Views: 323

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371049

fetch returns a Response object, not a Blob - if you try to use blob methods like .slice and .stream on the result, errors will be thrown, since those methods do not exist.

// Not OK:
fetch('data:,Hello%2C%20World!').then(blob => blob.slice()).catch((err) => console.log('err', err.message));
// OK:
fetch('data:,Hello%2C%20World!').then(res => res.text()).then(console.log);

Note that the Response can be converted into a Blob, but the return value from fetch would still be a Response:

fetch(endpoint)
  .then(response => response.blob())
  .then((blob) => {
    // work with the blob here
  });

Calling the response a blob is incorrect. They're somewhat similar, but not the same. Better to avoid calling it a blob to avoid confusion.

Upvotes: 3

Related Questions