Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch().then() return content-type and body [duplicate]

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?

like image 396
Simmetric Avatar asked Aug 22 '18 17:08

Simmetric


People also ask

What is the return type of fetch () function?

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.

What type of object does a fetch call return?

The Response Object returned by a fetch() call contains all the information about the request and the response of the network request.

What does a fetch request return?

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.


2 Answers

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.

like image 59
t.niese Avatar answered Sep 28 '22 17:09

t.niese


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);
    });
like image 28
Shant Marouti Avatar answered Sep 28 '22 18:09

Shant Marouti