18

This is how I access the result from a fetch call:

let data;

fetch(someUri)
    .then((response) => response.json())
    .then(_data => {
        data = _data;
    })
    .catch(error => {
        console.error(error);
    });

Is it also possible to access the result from the fetch function itself, like this:

let data = fetch(someUri)
    .then((response) => response.json())
    .then(data => {
        // do some stuff
        return data;
    })
    .catch(error => {
        return error;
    });

So data will be either the JSON data or the error. I see in my Chrome console that the result is in the variable, but I don't know how to access it because it's wrapped with other information.

VLAZ
  • 26,331
  • 9
  • 49
  • 67

3 Answers3

25

You can wrap it inside an immediately invoked async function and use await:

https://jsfiddle.net/ibowankenobi/ok72rfp6/

!async function(){
let data = await fetch("https://raw.githubusercontent.com/IbrahimTanyalcin/LEXICON/master/lexiconLogo.png")
    .then((response) => response.blob())
    .then(data => {
        return data;
    })
    .catch(error => {
        console.error(error);
    });

console.log(data);
}();
ibrahim tanyalcin
  • 5,643
  • 3
  • 16
  • 22
  • Thank you. => response.json() would be useful to many. Currently you proceed even if there's no data, the example might be improved with a check or better yet, replacing return data; with code to process the data on success. Why !async? It's not required. – Henrik Erlandsson Sep 13 '22 at 15:02
  • Can `data` be accessed outside async function? – Dounchan Jan 07 '23 at 00:18
  • @Dounchan , `return` from the async: `const mydata = (async function(){... return data})()` – ibrahim tanyalcin Jan 07 '23 at 09:53
7

Here are some good resources for fetch and an example.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API https://developer.mozilla.org/en-US/docs/Web/API/Body/text https://developer.mozilla.org/en-US/docs/Web/API/Body/json

You may also want to get familiar with promises. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

 
    function doSomethingWithText(text) {
        console.log('The text is:', text);
    }

    fetch('someUrl.html')
      .then(data => data.text())
      .then(doSomethingWithText)
      .catch(error => new Error(error));
colecmc
  • 3,133
  • 2
  • 20
  • 33
1

fetch method returns a promise that resolves to a Response object.

Once you get the response, it is up to you what to do with it. You can use methods on response body like json, text or blob to get data into desired format to work with.

snnsnn
  • 10,486
  • 4
  • 39
  • 44