Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  123] [ 6]  / answers: 1 / hits: 21662  / 6 Years ago, wed, august 22, 2018, 12:00:00

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?


More From » promise

 Answers
79

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.


[#53670] Sunday, August 19, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dylondaytond

Total Points: 92
Total Questions: 88
Total Answers: 96

Location: China
Member since Fri, Jan 15, 2021
3 Years ago
;