互联网上的每个 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 是一个承诺。如何在同一上下文中获取这两个值?
你可以这样写:
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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)