fetch().then() return content-type and body [duplicate]

安稳与你 提交于 2020-01-15 05:11:08

问题


Every fetch API example on the internet shows how to return only the body using response.json(), response.blob() etc. What I need is to call a function with both the content-type and the body as a blob and I cannot figure out how to do it.

fetch("url to an image of unknown type")
  .then((response) => {
    return {
      contentType: response.headers.get("Content-Type"),
      raw: response.blob()
  })
  .then((data) => {
    imageHandler(data.contentType, data.raw);
  });

This obviously doesn't work: data.contentType is filled, but data.raw is a promise. How can I get both values in the same context?


回答1:


You could write it that way:

fetch("url to an image of unknown type")
  .then(response => {
    return response.blob().then(blob => {
      return {
        contentType: response.headers.get("Content-Type"),
        raw: blob
      }
    })
  })
  .then(data => {
    imageHandler(data.contentType, data.raw);
  });

Or this way

fetch("url to an image of unknown type")
  .then(response => {
    return response.blob().then(blob => {
        imageHandler(response.headers.get("Content-Type"), blob)
    })
  })

In both cases you keep the callback in which you receive the resolved blob within the scope where you have access to response.




回答2:


Wait for the blob then create the object :

fetch("url to an image of unknown type")
.then(response => {
  return response.blob()
  .then(raw => ({
    contentType: response.headers.get("Content-Type"),
    raw
  }));
).then(data => imageHandler(
  data.contentType,
  data.raw
));



回答3:


If you are allowed to use async functions the best solution is to use async/await

async function fetchData() {
    const res = await fetch('url');
    const contentType = res.headers.get('Content-Type');
    const raw = await res.blob();
    // you have raw data and content-type

    imageHandler(contentType, raw);
}

If not:

fetch('')
    .then((res) => res.blob().then((raw) => {
        return { contentType: res.headers.get('Content-Type'), raw };
    }))
    .then((data) => {
        imageHandler(data.contentType, data.raw);
    });


来源:https://stackoverflow.com/questions/51972619/fetch-then-return-content-type-and-body

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