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

霸气de小男生 提交于 2021-01-29 15:46:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/61035624/what-should-the-intermediate-result-that-a-fetch-request-returns-be-called-a-bl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!