fetch().then() return content-type and body
12,117
Solution 1
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
.
Solution 2
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);
});
Solution 3
Wait for the blob then create the object :
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
));
Related videos on Youtube
Author by
Simmetric
Updated on June 04, 2022Comments
-
Simmetric almost 2 years
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?
-
Simmetric over 5 yearsThank you, I didn't think about doing a then() call inside another then(). And +1 for giving two examples.