【问题标题】:fetch().then() return content-type and body [duplicate]fetch().then() 返回内容类型和正文 [重复]
【发布时间】:2019-01-29 01:19:25
【问题描述】:

互联网上的每个 fetch 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);
  });

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

【问题讨论】:

    标签: javascript promise fetch


    【解决方案1】:

    你可以这样写:

    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 的范围内。

    【讨论】:

    • 谢谢,我没想过在另一个 then() 中调用 then()。 +1 举两个例子。
    【解决方案2】:

    如果允许您使用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);
        });
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2013-02-18
        • 2021-02-17
        • 1970-01-01
        • 1970-01-01
        • 2021-12-21
        • 2020-08-10
        • 2019-07-03
        • 2021-06-16
        • 1970-01-01
        相关资源
        最近更新 更多