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);
});
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?
Return value The fetch() method returns a promise that can either be resolved or not. Thus, this method always returns a value and the only possible case where it may fail to return anything is a server error.
The Response Object returned by a fetch() call contains all the information about the request and the response of the network request.
The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise that resolves to the Response to that request — as soon as the server responds with headers — even if the server response is an HTTP error status.
You could write it that way:
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);
});
Or this way
fetch("url to an image of unknown type")
.then(response => {
return response.blob().then(blob => {
imageHandler(response.headers.get("Content-Type"), blob)
})
})
In both cases you keep the callback in which you receive the resolved blob
within the scope where you have access to response
.
If you are allowed to use async
functions the best solution is to use 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);
}
If not:
fetch('')
.then((res) => res.blob().then((raw) => {
return { contentType: res.headers.get('Content-Type'), raw };
}))
.then((data) => {
imageHandler(data.contentType, data.raw);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With