Search code examples
fetch-apiasynccallback

How to return value out of an asynchron function


I have this function to retrieve data, but I get following failure message:

Uncaught TypeError: Cannot read property 'done' of undefined.

It looks like, that the return function is not working. Would be happy for some help. I still have my trouble with callback functions.

Thanks for your help!

function getData(evt){
    fetch (evt)
    .then (function (response) {
        return response.json();
    });
}
getData("/getfile/xy").done(function(data){
    // do something
    console.log(data);
});


Solution

  • you do it with Async & await way:-

    async function getData(evt) {
      return await fetch (evt)
      .then (response => response.json())
      .then(data => {
        return data
      })
    }
    
    // retrieve it anywahere (this must be in an 'async' function to work)
    let dataRetrieved = await getData("/getfile/xy")