fetch()。then()返回内容类型和主体

Sim*_*ric 2 javascript fetch promise

互联网上的每个提取API示例都展示了如何使用response.json(),response.blob()等仅返回主体。我需要的是同时调用内容类型和主体为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);
  });
Run Code Online (Sandbox Code Playgroud)

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

t.n*_*ese 6

您可以这样写:

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);
  });
Run Code Online (Sandbox Code Playgroud)

或者这样

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

在这两种情况下,您都应将回调保留blob在您有权访问的范围内,以便在其中接收已解决的问题response


Sha*_*uti 6

如果允许您使用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);
}
Run Code Online (Sandbox Code Playgroud)

如果不:

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