fetch().then()返回内容类型和主体 [英] fetch().then() return content-type and body

查看:335
本文介绍了fetch().then()返回内容类型和主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这显然行不通: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?

推荐答案

您可以这样写:

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

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

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

这篇关于fetch().then()返回内容类型和主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆