fetch().then() return 内容类型和正文

fetch().then() return content-type and body

互联网上的每个提取 API 示例都显示了如何使用 response.json()、response.blob() 等仅 return 正文。 我需要的是调用一个将内容类型和正文都作为 blob 的函数,但我不知道该怎么做。

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);
  });

这显然行不通:data.contentType 已填满,但 data.raw 是承诺。如何在同一上下文中获取两个值?

等待 blob,然后创建对象:

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
));

你可以这样写:

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);
  });

或者这样

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

在这两种情况下,您都将收到已解决 blob 的回调保留在您有权访问 response.

的范围内

如果允许使用 async 函数,最好的解决方案是使用 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);
}

如果没有:

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